角2 - 如何id属性设置为动态加载组件 [英] Angular 2 - How to set id attribute to the dynamically loaded component

查看:216
本文介绍了角2 - 如何id属性设置为动态加载组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 DynamicComponentLoader 加载子组件,它产生下面的HTML:

 <儿童成分>儿童内容此处< /儿童成分>

在这里是怎么了加载组件在父

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

我怎样才能id属性添加到子组件,使其产生下面的HTML:

 <儿童组件id =someId>儿童内容此处< /儿童成分>


解决方案

如果可能,我将一个字段添加到 ChildComponent 和绑定 ID 来的:

  @Component({
  选择:儿童分量',
  主持人:{'attr.id':'ID'}
})
类ChildComonent {
  ID:字符串;
}

  this._loader.loadIntoLocation(ChildComponent,this._elementRef,'孩子')
。然后(CMP => cmp.instance.id ='someId');

另请参阅 http://plnkr.co/edit/ihb7dzRlz1DO5piUvoXw?p= $ p $#PVIEW

一个更哈克的方式是

  this.dcl.loadIntoLocation(动态,this.ref,'孩子'),那么((CMP)=> {
  cmp.location.nativeElement.id ='someId';
});

而不是 nativeElement 属性访问,直接就应该可以做同样的渲染

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>

解决方案

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

@Component({
  selector: 'child-component',
  host: {'attr.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.

这篇关于角2 - 如何id属性设置为动态加载组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆