javascript - 我可以 'observe' 组件的动态子项吗?

标签 javascript angular angular2-ngcontent

我有一个应用程序,我在其中使用多个表单组件组成表单。现在我想创建某种外键字段,它列出已经存在的对象并显示一个“添加”按钮。此按钮在模态对话框中显示另一个表单组件。该“子”表单仅使用 <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/

相关文章:

angular - 如何有条件地在 ng-content 周围包装一个 div

Angular 4 ngComponentOutlet 加载动态组件,但未呈现路由内容

javascript - php 聊天导致浏览器在 wamp 32 位上测试时卡住

javascript - 请求的资源上不存在 'Access-Control-Allow-Origin' header 。响应的 HTTP 状态代码为 405

javascript - 如何以编程方式获取 json 对象列表的属性?

angular - 将第三方库导入 Angular 库会报错

angular - 在 Angular 7 中,当使用 Observable 时,页面会在没有请求的情况下刷新

javascript - *ngFor 在 ng-content Angular 的元素上

在 Angular 项目上运行的 JavaScript JSDoc

angular - 如何将标题子菜单添加到 Angular 6 中的 material-dashboard-angular2 侧栏