5

我有一个应用程序,我在其中使用多个表单组件编写表单。现在我想创建某种外键字段,它列出了已经存在的对象并显示了一个“添加”按钮。此按钮在模式对话框中显示另一个表单组件。该“子”表单仅使用显示<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()for it'ssave事件。这是一个EventEmitter.

我的问题是:如何EventEmitter<form-field>组件订阅这个?我想知道何时保存表单,以便我可以关闭<modal-dialog>.

请记住:表单是使用<ng-content>. 我可以@ViewChildren用来获取孩子<form-field>并使用某种addEventListener()方法吗?这样的事情甚至存在吗?

希望你能帮我!

问候,约翰

4

1 回答 1

1

您可以从组件类中查询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);
        });
    }
 }

AnotherFormComponent每当添加、删除或移动QueryList时都会更新。您可以通过订阅QueryList.changesObservable 来“观察”变化:

ngAfterContentInit() {
    this.anotherFormComponents.changes.subscribe(qList => {
        console.log('Changed list: ', qList);
    });
}

顺便说一句,值得知道:@ViewChild 和 @ContentChild 有什么区别?

于 2017-01-18T17:01:21.147 回答