Pages

Wednesday, June 8, 2022

@ViewChild in Angular

Using display:none in Angular does not completely remove the elements in the DOM. It is still there and ready to be "re-active" using JavaScript. So you need *ngIf if in this case.

When conditional rendering data using *ngIf in Angular (>=2), you cannot query the DOM inside and at the same time appending something to those elements inside. 

You might need to use the decorator @ViewChild() such as in follows: 

 @ViewChild('control_bottom_html')  control_bottom_variable: ElementRef;

You need to declare  #control_bottom_html (with the hashtag) in the DOM where you want to manipulate directly whereas control_bottom_variable is the variable that can be then used to update the DOM already injected. 

Now inside the phrase  ngAfterViewInit() (not the phrase ngOnInit()) , you can call query the div injected with #control_bottom_html.

 this.controlPanel = this.control_bottom_variable.nativeElement; 

Then you can manipulate it such as appending elements or implements events.

From Angular Docs, it seems that you should use Render2 rather than ElementRef for safety reason.

https://angular.io/api/core/ElementRef