Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to capture nativeElement for custom angular components

I am unable to get the reference of nativeElement of my custom Elements. I have a template like this:

<div #testone>
<my-feature-cmp><my-feature-cmp>
<my-feature-cmp><my-feature-cmp>
<my-feature-cmp><my-feature-cmp>
<div>

Code used to access: @ViewChild('testone') el: ElementRef;

I get the element reference when I do this -> console.log(this.el.nativeElement)

Second type of template

<my-feature-cmp></my-feature-cmp>
<my-feature-cmp></my-feature-cmp>
<my-feature-cmp></my-feature-cmp>

Code used to access:

@ViewChildren(MyFeatureCmp) el: MyFeatureCmp;

I get the error for native element when I do this ->

console.log(this.el.nativeElement)

I get the class references and no nativeElement when I do this ->

console.log(this.el)
console.log(this.el.toArray())

The question is how to I access the native element of custom component if I want to make changes to the tag attributes. Second, whatever way I access them, If I change the attributes manually for custom component will it get detected as a change as well after the change?

like image 473
Gary Avatar asked Jul 13 '17 04:07

Gary


1 Answers

The question is how to I access the native element of custom component

You have to use read option:

@ViewChildren(MyFeatureCmp, {read: ElementRef}) el: QueryList<ElementRef>;

console.log(this.el.first.nativeElement)

Also see this answer to learn what we can get using read.

If I change the attributes manually for custom component will it get detected as a change as well after the change?

No, Angular doesn't process changes on DOM elements. For more information on what change detection processes see Everything you need to know about change detection in Angular.

like image 152
Max Koretskyi Avatar answered Sep 19 '22 14:09

Max Koretskyi