【问题标题】:Reading a child component data from parent component in Angular 4从Angular 4中的父组件读取子组件数据
【发布时间】:2018-03-19 20:51:40
【问题描述】:

我有一个父页面来列出网格中的项目,并且在其编辑/新事件中,我必须在模型中显示一个带有网格的模型。网格本身是另一个组件。

除了网格之外,模型上还有两个文本框,它们是包含子组件(网格)的父组件的一部分。 跟随屏幕抓取,其中红色标记的是子组件。

这里是子组件选择器声明

@Component({
    selector: 'app-userlist',
    templateUrl: 'userlist.component.html'
})

在模型上,当我们提交这个事件时触发

onSubmit(): void {

    this.http.post(this.baseUrl + "api/TemplateCategory", this.templatecategory).subscribe(result => {
        //todo did it save properly or return an error?

        $("#newTemplateCategoryModal").modal("hide");
        this.templatecategorySaved.emit(this.templatecategory);
    }, error => {
        alert("post error\nStatus Code: " + error.status + "\nMessage:" + error._body);
    });
}

所以我的问题是我们如何在保存时获取网格(子组件)值。在网格中有一个用于为每个用户选择角色的下拉菜单。

【问题讨论】:

    标签: angular


    【解决方案1】:

    在父组件上你可以有一个 ViewChild 指令 喜欢

    @ViewChild('identifier') child: ChildType;

    在模板上为您的孩子添加标识符

       <app-userlist #identifier></app-userlist>
    

    然后你可以在你的函数中调用你的子方法或使用它自己的变量做 child.whatever

    【讨论】:

      【解决方案2】:

      我认为这是不可能的,因为如 Angular 文档中所述:

      局部变量方法简单易行。但它是有限的,因为父子连接必须完全在父模板内完成。父组件本身无权访问子组件。

      我习惯于使用服务来处理这种交互。您可以在父级创建一个服务来向/从子组件发送和接收数据,或者如果更有意义的话,可以在子级创建它。

      我可以为您提供几个示例,但在我看来,Angular 文档总是有很好的示例。关注此link 通过服务进行交互。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-08-12
        • 2017-12-24
        • 1970-01-01
        • 2020-07-16
        • 1970-01-01
        • 2022-01-19
        • 2019-05-05
        • 2021-03-03
        相关资源
        最近更新 更多