Monday, 1 February 2021

Angular how to dynamically get HTML element widith and height && ViewChild static true Vs false

 html 

<div 

#element>



component.ts

@ViewChild('element', {static:false}) element: ElementRef;



// Width

this.element.nativeElement.offsetWidth;


// Height

this.element.nativeElement.offsetHeight;


https://www.itsolutionstuff.com/post/how-to-get-element-height-and-width-in-angularexample.html


In most cases you will want to use {static: false}. Setting it like this will ensure query matches that are dependent on binding resolution (like structural directives *ngIf, etc...) will be found.

Example of when to use static: false:

@Component({
  template: `
    <div *ngIf="showMe" #viewMe>Am I here?</div>
    <button (click)="showMe = !showMe"></button>
  ` 
})
export class ExampleComponent {
  @ViewChild('viewMe', { static: false })
  viewMe?: ElementRef<HTMLElement>; 

  showMe = false;
}

The static: false is going to be the default fallback behaviour in Angular 9. Read more here and here

The { static: true } option was introduced to support creating embedded views on the fly. When you are creating a view dynamically and want to acces the TemplateRef, you won't be able to do so in ngAfterViewInit as it will cause a ExpressionHasChangedAfterChecked error. Setting the static flag to true will create your view in ngOnInit.

Nevertheless:

In most other cases, the best practice is to use {static: false}.


No comments:

Post a Comment