当我指定类似ID时,ViewChild起作用
<div #test_205626>test</div>
但是当我这样做时:
<div [attr.id]="test_id">test</div>
我得到类似的东西
<div _ngcontent-gtn-c6="" id="test_205626">test</div>
在输出html中,但同时出现错误:
无法读取未定义的属性'nativeElement'
代码是:
test_id = 'test_205626';
@ViewChild('test_205626', {read: ElementRef, static: false}) private myScrollContainer3: ElementRef;
为什么ViewChild不能与[attr.id]一起使用?
答案 0 :(得分:2)
摘自Angular.io上的 ViewChild
文档:
支持以下选择器。
- 任何带有
@Component
或@Directive
装饰器的类- 模板引用变量作为字符串(例如,以
<my-component #cmp></my-component>
查询@ViewChild('cmp')
)- 在当前组件的子组件树中定义的任何提供程序(例如
@ViewChild(SomeService) someService: SomeService
)- 通过字符串令牌定义的任何提供程序(例如
@ViewChild('someToken') someTokenVal: any
)- TemplateRef(例如查询
<ng-template></ng-template>
和@ViewChild(TemplateRef) template;
)
您尝试使用的id属性选择器实际上不适用于@ViewChild
。
您只需要坚持使用<div #test_205626>test</div>
。