向动态创建的组件添加事件和变量 Angular 4
Add Events and Variable to Dynamically created Component Angular 4
我的 Angular 应用程序中有一个动态创建的组件,如下所示:
const factory = this.resolver.resolveComponentFactory<IMessage>(MessageComponent);
this.component = this.container.createComponent(factory);
this.component.instance.body = message;
相当于在组件的HTML中添加<message [body]="message"></message>
。
假设我想在我的动态组件代码中实现这样的目标:
<message [body]="message" #form="my-form" (change)="myFunction()"></message>
如何通过组件的 ts 文件绑定这些附加变量并更改内部事件?
输入绑定和事件输出不会自动与动态创建的组件一起工作。这是因为编译器创建了监听子组件事件的函数和根据它解析的模板更新子组件绑定的函数。模板中未指定动态组件,因此编译器不会创建此类函数。您可以在此处阅读有关这些功能的信息 -
The mechanics of property bindings update in Angular。函数名称是 updateDirectives
.
您必须手动更新属性并订阅事件:
this.component.instance.body = message;
this.component.instance.change.subscribe();
这意味着子组件不能使用 ngOnChanges
生命周期挂钩,因为它永远不会被 Angular 触发。
此外,像这些 #form
这样的查询列表绑定也不起作用。您只能访问组件的实例。因此,任何将自身导出为 my-form
的指令都应该注入主机 MessageComponent
并将与 my-form
关联的数据附加到组件实例。然后父组件就可以访问它了:
this.component.instance.formData;
我的 Angular 应用程序中有一个动态创建的组件,如下所示:
const factory = this.resolver.resolveComponentFactory<IMessage>(MessageComponent);
this.component = this.container.createComponent(factory);
this.component.instance.body = message;
相当于在组件的HTML中添加<message [body]="message"></message>
。
假设我想在我的动态组件代码中实现这样的目标:
<message [body]="message" #form="my-form" (change)="myFunction()"></message>
如何通过组件的 ts 文件绑定这些附加变量并更改内部事件?
输入绑定和事件输出不会自动与动态创建的组件一起工作。这是因为编译器创建了监听子组件事件的函数和根据它解析的模板更新子组件绑定的函数。模板中未指定动态组件,因此编译器不会创建此类函数。您可以在此处阅读有关这些功能的信息 -
The mechanics of property bindings update in Angular。函数名称是 updateDirectives
.
您必须手动更新属性并订阅事件:
this.component.instance.body = message;
this.component.instance.change.subscribe();
这意味着子组件不能使用 ngOnChanges
生命周期挂钩,因为它永远不会被 Angular 触发。
此外,像这些 #form
这样的查询列表绑定也不起作用。您只能访问组件的实例。因此,任何将自身导出为 my-form
的指令都应该注入主机 MessageComponent
并将与 my-form
关联的数据附加到组件实例。然后父组件就可以访问它了:
this.component.instance.formData;