Can I "observe" the dynamic children of a component?

I have an application in which I compose forms using several form components. Now I want to create some kind of foreign key field, which lists already existing objects, as well as the "add" button. This button displays another form component in a modal dialog box. The form 'sub' is simply displayed with <ng-content>. It all works great.

I will illustrate the situation. This is the template <form-component>:

<form class="form">
    <form-field>
        <another-form-component (save)="handleSave()"></another-form-component>
    </form-field>
</form>

Template <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>

As you can see, it <another-form-component>has @Output()an event for him save. That EventEmitter.

: EventEmitter <form-field>? , , <modal-dialog>.

: <ng-content>. @ViewChildren <form-field> - addEventListener()? - ?

, !

, Johan

+4
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);
        });
    }
 }

QueryList , AnotherFormComponent , . "" , QueryList.changes Observable:

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

Btw, : @ViewChild @ContentChild?

+2

Source: https://habr.com/ru/post/1667160/


All Articles