title: How to change template when width of elementRef changed
body: <p>I try to load some data in ngInit and set width of the div equal to received data. Then I try to set some style options in ngAfterViewInit using ViewChild and ElementRef, but my elementRef is always undefined. How can I fix it?</p>
  <p>MyComponent:</p>
  <pre><code>export class NewComponent implements OnInit, AfterViewInit {
      public data: number = 0;
      public showMe: bool = false;
      public redColor: bool = false;
      @ViewChild('myElement', { static: false}) myElement;
  
      constructor(private myService: MyService) {}
  
      public ngOnInit(): void {
          this.myService.loadData().subscribe(result =&gt; this.data = result);
      }
  
      public ngAfterViewInit(): void {
          console.log(this.myElement); // undefined
          console.log(this.myElement.nativeElement); // Cannot read property 'nativeElement' of undefined
          this.setStyleOptions(); 
      }
  
      public setStyleOptions() {
          if (this.myElement.nativeElement.clientWidth &gt; 50) {
              this.showMe = true;
              this.redColor = true;
          }
          else {
              this.showMe = false;
              this.redColor = false;
          }
      }
  }
  </code></pre>
  <p>My template:</p>
  <pre><code>&lt;div *ngIf=&quot;some-condition&quot;&gt;
      &lt;div *ngIf=&quot;some-new-condition&quot;&gt;
          &lt;div #myElement [style.width.px]=data&quot;&gt;&lt;/div&gt;
          &lt;div *ngIf=&quot;showMe&quot; [class.red]=&quot;redColor&quot;&gt;Text&lt;/div&gt;
      &lt;/div&gt;
  &lt;/div&gt;
  </code></pre>
  <p>I know that elementRef can be undefined due to *ngIf directive, but I can`t replace it by [hidden], because I will have to replace the directive in all outer div blocks. I also try to use ViewChild setter, like here <a href="https://stackoverflow.com/questions/39366981/viewchild-in-ngif">@ViewChild in *ngIf</a>:</p>
  <pre><code>private myElement: ElementRef;
  @ViewChild('myElement', { static: false}) set content(content: ElementRef) {
      if (content) {
          this.myElement = content;
          this.setStyleOptions();
      }
  }
  </code></pre>
  <p>But then &quot;Еxpression has changed after it was checked&quot; appears in console.
  Set timeout also doesn`t help.</p>
  <p>How can I change template properly?</p>