essaji essaji - 7 months ago 14
Javascript Question

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>

Answer

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.