[英]How to reference element for create dynamic component in Angular2
<div *ngFor="let w of widgets">
<div #elem [id]="w.componentName"></div>
</div>
I want to create dynamic component by reference attribute [id] . 我想通过引用属性[id]创建动态组件。
为什么不创建一个新组件并嵌入到*ngFor
,并通过@Input()
将ID传递到新组件中呢?
You can create a service : 您可以创建服务:
@Injectable() export class WidgetService { getWidget(id) : IWidget { // return your constructed widget instead return {componentName : id}; } }
Now create a widget component that takes in ID and sends request to the above service to get widget : 现在创建一个小部件组件,该小部件组件将使用ID,并将请求发送到上述服务以获取小部件:
@Component({ selector: 'widget', template: ` <div> <h2>{{data.componentName}}</h2> </div> `, providers: [WidgetService] }) export class WidgetComponent implements OnInit{ @Input() id: string; data: IWidget; constructor(private wService : WidgetService) {} ngOnInit() { this.data = this.wService.getWidget(this.id); } }
Using interface to pass information as widget interface here.. 在这里使用接口将信息作为小部件接口传递。
export interface IWidget { componentName : string }
Now modify your code to accept WidgetComponent inside *ngFor : 现在修改您的代码以接受* ngFor中的WidgetComponent:
@Component({ selector: 'my-app', template: ` <div *ngFor="let w of widgets"> <widget [id]="w.componentName"></widget> </div> `, }) export class App { widgets:IWidget[]; constructor() { this.widgets = [ {componentName : "w1"}, {componentName : "w2"}, {componentName : "w3"} ] } }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.