angular - 在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 组件的输入。
解决方案
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 { }
推荐阅读
- javascript - JSON.parse 返回未定义
- javascript - Threejs当父矩阵改变时,子不应用
- javascript - 将代码添加到底部导航android studio
- google-cloud-firestore - Firestore 模拟器 - 模拟连接丢失
- reactjs - Heroku 在构建期间无法编译
- python - Python:如何将 str json 写入 csv 文件?
- c# - Windows 桌面上下文菜单
- eclipse - 当我输入“if”时,Eclipse 显示非常糟糕的自动完成
- javascript - Vue.js:更新商店后如何避免错误?
- forms - 使用邮递员从网站表单复制发布请求返回 500 内部服务器错误