1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

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

Discussão em 'Angular' iniciado por Sandeep Thomas, Julho 19, 2025.

  1. 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.

    Continue reading...

Compartilhe esta Página