首页 > 解决方案 > 在Angular中动态创建的自定义组件上设置属性

问题描述

我有一个属于自定义库的组件:

<my-icon>

为了有图标,我应该设置[name]这个组件的属性。像这样的东西:

<my-icon [name]='warning'></my-icon>

我正在使用 TypeScript 动态创建这些图标:

if (myCondition) {
    let icon = <HTMLElement>document.createElement('my-icon');
}

[name]我应该如何在我的变量中设置属性icon以获得与上述相同的结果?我已经尝试过icon.setAttribute('name','warning'),但它不起作用(设置 HTML 属性name,而不是name底层 Angular 组件的输入。

标签: angulartypescript

解决方案


document.create不创建 Angular 组件,而只创建 DOM 元素。如果你想动态创建 Angular 组件,你应该注入ComponentFactoryResolver服务

constructor(private componentResolver: ComponentFactoryResolver) { }

以后可以这样使用:

// create factory for icon component
const factory = this.componentResolver.resolveComponentFactory(MyIconComponent);

// create icon component and append it next to anchor element
const icon = this.anchor.createComponent(factory);

// assign some value to component input
icon.instance.name = 'icon name';

ViewChild如果您的组件模板如下所示,则可以使用例如获取锚元素:

`<div #iconsHere></div>`

您必须添加以下注释:

  @ViewChild('iconsHere', {read: ViewContainerRef}) anchor: ViewContainerRef;

请注意,动态创建的组件必须在模块中声明为入口组件。

@NgModule({
  ...
  entryComponents: [ MyIconComponent ]
})
export class AppModule { }

演示: https ://stackblitz.com/edit/angular-jukjib


推荐阅读