我无法获取自定义元素的 nativeElement 引用。我有一个这样的模板:
<div #testone>
<my-feature-cmp><my-feature-cmp>
<my-feature-cmp><my-feature-cmp>
<my-feature-cmp><my-feature-cmp>
<div>
用于访问的代码: @ViewChild('testone') el: ElementRef;
当我这样做时我得到了元素引用 -> console.log(this.el.nativeElement)
第二种模板
<my-feature-cmp></my-feature-cmp>
<my-feature-cmp></my-feature-cmp>
<my-feature-cmp></my-feature-cmp>
用于访问的代码:
@ViewChildren(MyFeatureCmp) el: MyFeatureCmp;
当我这样做时,我得到了原生元素的错误 ->
console.log(this.el.nativeElement)
当我这样做时,我得到了类引用但没有 nativeElement ->
console.log(this.el)
console.log(this.el.toArray())
问题是如果我想更改标签属性,如何访问自定义组件的原生元素。其次,无论我以何种方式访问它们,如果我手动更改自定义组件的属性,它是否也会在更改后被检测为更改?
最佳答案
The question is how to I access the native element of custom component
你必须使用read
选项:
@ViewChildren(MyFeatureCmp, {read: ElementRef}) el: QueryList<ElementRef>;
console.log(this.el.first.nativeElement)
另请参阅 this answer 以了解我们可以使用 read
获得什么。
If I change the attributes manually for custom component will it get detected as a change as well after the change?
不,Angular 不处理 DOM 元素上的更改。有关更改检测过程的更多信息,请参阅 Everything you need to know about change detection in Angular。
关于javascript - 无法为自定义 Angular 组件捕获 nativeElement,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45071679/