Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 - How to set id attribute to the dynamically loaded component

I am using DynamicComponentLoader to load the child component and it produces the following html:

<child-component> Child content here </child-component>

and here is how I am loading the component in the parent

ngAfterViewInit(){
        this._loader.loadIntoLocation(ChildComponent,this._elementRef,'child');
  }

How can I add the id attribute to the child component so that it produces the following html:

<child-component id="someId" > Child content here </child-component>
like image 705
Eesa Avatar asked Feb 29 '16 15:02

Eesa


1 Answers

If possible I would add a field to ChildComponent and bind id to it:

@Component({
  selector: 'child-component',
  host: {'[id]': 'id'}
})
class ChildComonent {
  id:string;
}
this._loader.loadIntoLocation(ChildComponent,this._elementRef,'child')
.then(cmp => cmp.instance.id = 'someId');

See also http://plnkr.co/edit/ihb7dzRlz1DO5piUvoXw?p=preview#

A more hacky way would be

this.dcl.loadIntoLocation(Dynamic, this.ref, 'child').then((cmp) => {
  cmp.location.nativeElement.id = 'someId';
});

Instead of accessing nativeElement properties directly it should be possible to do the same with Renderer.

like image 180
Günter Zöchbauer Avatar answered Sep 23 '22 02:09

Günter Zöchbauer