angular - @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作为属性
请让我知道如何解决这个问题。
解决方案
如果您在此处查看支持的选择器的文档@ViewChild()
:https ://angular.io/api/core/ViewChild#description ,您可以看到您需要传递模板引用变量。
class
或者id
不支持作为选择器!
推荐阅读
- javascript - 如何更改 React Dropdown 的标题?
- elasticsearch - LXD 问题,带有 Elasticsearch 的 vm.max_map_count
- haskell - foldr (.) id 的类型
- python - Dask 分布式计算性能在循环中下降
- reactjs - React Final Form:根据表单值做条件
- .htaccess - 当 URL 与类别匹配时如何将请求重定向到特定页面
- unity3d - Unity 2019 - 换行符 \n 不适用于 UI 文本元素
- mysql - 选择 MySQL 值,其中值等于一个值但不等于其他值
- python - 如何使用 numpy 数组中的 RGBA 数据列表进行 alpha 合成?
- python - 将字符串日期转换为日期并在数据框中删除时间