Javascript 角度2-如何为动态加载的组件设置id属性

Javascript 角度2-如何为动态加载的组件设置id属性,javascript,angular,Javascript,Angular,我正在使用DynamicComponentLoader加载子组件,它会生成以下html: <child-component> Child content here </child-component> <child-component id="someId" > Child content here </child-component> 如何将id属性添加到子组件中,使其生成以下html: <child-component> Chi

我正在使用
DynamicComponentLoader
加载子组件,它会生成以下html:

<child-component> Child content here </child-component>
<child-component id="someId" > Child content here </child-component>
如何将id属性添加到子组件中,使其生成以下html:

<child-component> Child content here </child-component>
<child-component id="someId" > Child content here </child-component>
此处为子内容

如果可能,我会在
ChildComponent
中添加一个字段,并将
id
绑定到该字段:

@Component({
  selector: 'child-component',
  host: {'[id]': 'id'}
})
class ChildComonent {
  id:string;
}
另见

一种更令人讨厌的方式是

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

与其直接访问
nativeElement
属性,还可以使用
Renderer

主机:{'attr.id':'id'}做什么?它将
标记的
id
属性设置为
this.id
的值。但是答案中的语法错误(在Plunker中正确)但是
attr.
是多余的,因为
它是任何元素上的属性,并自动反映到
id
属性。更新了我的答案。@GünterZöchbauer您能演示一下如何对多个css类执行相同的操作吗?例如,仅供参考,我的TSLint建议在主机组件参数上使用
@HostBinding
,这个语法对于我来说是这样的
@HostBinding('attr.id')id
这与
@Input
参数在组件中的作用一样