我有一个应用程序,我在其中使用多个表单组件组成表单。现在我想创建某种外键字段,它列出已经存在的对象并显示一个“添加”按钮。此按钮在模态对话框中显示另一个表单组件。该“子”表单仅使用 <ng-content>
显示。 .这一切都很完美
我将说明情况。这是<form-component>
的模板:
<form class="form">
<form-field>
<another-form-component (save)="handleSave()"></another-form-component>
</form-field>
</form>
<form-field>
的模板:
<modal-dialog-component [(visible)]="showForm">
<!--
Here the <another-form-component> which was passed
to <form-field> is added:
-->
<ng-content></ng-content>
</modal-dialog-component>
<div class="form-field">
<select> <!-- existing options --> </select>
<button (click)="openForm($event);">Create new</button>
</div>
如你所见<another-form-component>
有一个 @Output()
因为它是 save
事件。这是 EventEmitter
.
我的问题是:如何订阅这个 EventEmitter
来自 <form-field>
成分?我想知道表格何时保存,以便我可以关闭 <modal-dialog>
.
记住:表单是使用 <ng-content>
传递的.我可以使用 @ViewChildren
吗?得到 <form-field>
的 children 并使用某种 addEventListener()
方法?是否存在这样的东西?
希望你能帮助我!
您好, 约翰
最佳答案
可以查询ContentChildren来自你的 <form-field>
组件类并订阅它们发出的事件如下:
export class FormFieldComponent implements AfterContentInit {
@ContentChildren(AnotherFormComponent) anotherFormComponents: QueryList<AnotherFormComponent>;
ngAfterContentInit() {
console.log('anotherFormComponents: ', this.anotherFormComponents.toArray());
this.anotherFormComponents.toArray()[0].save.subscribe(valueEmitted => {
console.log('Value emitted from the anotherFormComponents[0]: ', valueEmitted);
});
}
}
QueryList每当 AnotherFormComponent
时都会更新添加、删除或移动。您可以通过订阅 QueryList.changes
来“观察”变化。可观察的:
ngAfterContentInit() {
this.anotherFormComponents.changes.subscribe(qList => {
console.log('Changed list: ', qList);
});
}
顺便说一句,值得了解:What's the difference between @ViewChild and @ContentChild?
关于javascript - 我可以 'observe' 组件的动态子项吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41724072/