Sandeep Thomas
Sandeep Thomas

Reputation: 4759

@ViewChild using classname and ID not working when trying to appendChild

I am trying add a button to div with specific class

Here is my ViewChild initiated

  @ViewChild('.ttest', { static: true }) toolbarElement!: ElementRef;

and in my AfterViewInit

  ngAfterViewInit(): void {
    const button = this.renderer.createElement('button');
    const buttonText = this.renderer.createText('Email Reports');
    
    this.renderer.appendChild(button, buttonText);
    this.renderer.appendChild(this.toolbarElement.nativeElement, button);
  }

But its not seems to creating button inside my div with class ttest

But instead of class name if I specify my div like this

<div class='col' #ttest>..</div>

and on changing the view child into this

@ViewChild('ttest', { static: true }) toolbarElement!: ElementRef;

its working fine and a button getting created

Also when creating div like

 <div class='col' id='ttest'>...</div>
 @ViewChild('ttest', { static: true }) toolbarElement!: ElementRef;

its not working (like class)

So only situation its working is #ttest as attribute

Please let me know how to fix this.

Upvotes: 1

Views: 19089

Answers (1)

Adithya Sreyaj
Adithya Sreyaj

Reputation: 1892

If you check the documentation here for the supported selectors in @ViewChild() here: https://angular.io/api/core/ViewChild#description, you can see that you need to pass a template reference variable.

class or id are not supported as selector!

Upvotes: 8

Related Questions