/angular

The problem with Angular ViewChild and Template Variables

Today one of my friend was facing an interesting problem. As sometimes if we are struggling in something for hours, we may call for help from a friend, as its better to notice something minute with an extra pair of eyes.

Photo by Olav Ahrens Røtne on Unsplash

Introduction

As the title says we are working on a very large enterprise application whose front end is built in Angular. We have lot of nested and sub components which gets rendered in the HTML based on multiple conditions.

An example would look something like this

<div>
  <my-first-component>
  </my-first-compoent>
  <div *ngIf="!isProcessing">
    <message-component #messaging>
    </message-component>
  </div>
  lot of other stuffs...
</div>

If you are already familiar with Angular you might recognize the above HTML structure. The above is just a simple example. In a real time application there must be more than 1000+ lines of HTML code which renders various subcomponents.

emoji-neutral_face The problememoji-question

As i already said if you are familiar with angular you will understand the below code.

messages : Messages = new Messages();
@ViewChild('messaging') messageComponent : MessageComponent;
  • ViewChild is nothing but, it is used to access the childComponent from your parentComponent.
  • In the above two lines of code, one is just a variable initialized with the Messages class and the other is used to access the child component called MessageComponent

emoji-eyes ViewChild / Template Variable problem emoji-grey_exclamation

  • What we were doing is trying to access the value of the messages variable in the HTML.
  • An example would look something like this
<div>
  {{messages | json}}
  <div *ngIf="!isProcessing">
  {{messages | json}}
    <message-component #messaging>
    </message-component>
  </div>
</div>
  • Notice the line immeadiately after the first div the value can be seen in the UI.
  • But we were not able to get the value inside the second div ,i.e where the isProcessing is set to !(false)
  • We checked alot of things including ngOninit() and the object state, even validated the if condition twice.
  • Everything looked perfectly fine,but still we were not able to get the value inside the processing div.

emoji-thought_balloon The Solution

After an hour of debugging it strike’s me that the name of the ViewChild selector and the variable name is the same. Why not try changing this ? So we did so. We changed the selector name to #messageComponent and boom emoji-fire it works.

A working example can be found here at Stackblitz emoji-v

Thanks for reading and stay tuned for more blogs emoji-prayemoji-pray

HariHaran

HariHaran

Full Stack Developer

Read More