Dbrandt
Dbrandt

Reputation: 659

Getting HTML attr. with ViewContainerRef?

I am adding a component to my template via *ngFor

<div class="filter-group" *ngFor="let type of entityTypes">
  <filter-filter-group [type]="type" id="{{type.uri}}"></filter-filter-group>
</div>

And in my component I am getting my ViewChrildren like so

  @ViewChildren(FilterGroupComponent, { read: ViewContainerRef }) filterGroup: QueryList<ViewContainerRef>;

this.filterGroup now contains my components which is exactly what I want as I then use the component Factory to dynamically insert components to each viewChild.

As you can see in the tmpl. each component has an id="{{type.uri}}"
Is there a way to get the value of id?

I have searched far and wide and so far am a little lost on how to achieve this. NativeElement could be an option, but I believe that is only available with ElementRef?

Possible Solution:

console.log(group['_data'].renderElement.id);

this gives me the id.... but i don't think this would be the way to do it? I mean it works, but feels wrong.

Upvotes: 1

Views: 2585

Answers (3)

Shyam kumar
Shyam kumar

Reputation: 111

@ViewChildren("vc", {read: ViewContainerRef}) containers: QueryList<ViewContainerRef>
    
ngAfterViewInit(): void {
  this.containers.map(container => console.log(container["_lContainer"][0].id))
  this.createLayout();
}

This worked for me in Angular 10

Upvotes: 0

Francisco Santorelli
Francisco Santorelli

Reputation: 1338

The ViewContainerRef has an elementRef as a child, which in turn has a nativeElement child (the HTML element per se). So you should be able to do group.elementRef.nativeElement.id to get the id

Note: Be aware that using console.log(element) that returns an HTML element will print the element as HTML, for these cases instead use console.dir

Upvotes: 1

Yash Rami
Yash Rami

Reputation: 2317

you can try like this

HTML

<div class="filter-group" *ngFor="let type of entityTypes">
  <filter-filter-group [type]="type" #mycomp id="{{type.uri}}"></filter-filter-group>
</div>

TS

@ViewChildren('mycomp') mycompRef: any;

someEvent() {
   console.log(this.mycompRef); // in this object you will get the id
}

Upvotes: 1

Related Questions