微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript-Angular 2-如何将id属性设置为动态加载的组件

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

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

这是我在父级中加载组件的方式

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

如何将id属性添加到子组件,以便产生以下html:

<child-component id="someId" > Child content here </child-component>

解决方法:

如果可能的话,我会向ChildComponent添加一个字段并将其绑定ID:

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

另见http://plnkr.co/edit/ihb7dzRlz1DO5piUvoXw?p=preview#

一种更hacky的方式是

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

代替直接访问nativeElement属性,应该可以使用Renderer进行相同的操作.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐