在Angular

时间:2018-05-04 13:01:13

标签: angular typescript

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

<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,而不是基础Angular组件的输入name

1 个答案:

答案 0 :(得分:1)

document.create不会创建Angular组件,只会创建DOM元素。如果要动态创建Angular组件,则应注入ComponentFactoryResolver service

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

相关问题