首页 > 解决方案 > @ViewChild 在尝试 appendChild 时使用类名和 ID 不起作用

问题描述

我正在尝试向具有特定类的 div 添加一个按钮

这是我的 ViewChild 发起的

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

在我的 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);
  }

但它似乎不是在我的 div 中创建带有类ttest的按钮

但是如果我像这样指定我的 div 而不是类名

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

并将视图子更改为此

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

它工作正常并创建了一个按钮

同样在创建 div 时

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

它不工作(如类)

所以唯一的情况是它的工作是#ttest作为属性

请让我知道如何解决这个问题。

标签: angulartypescript

解决方案


如果您在此处查看支持的选择器的文档@ViewChild()https ://angular.io/api/core/ViewChild#description ,您可以看到您需要传递模板引用变量。

class或者id不支持作为选择器!


推荐阅读