首页 文章

从Angular 4中的父组件读取子组件数据

提问于
浏览
0

我有一个父页面列出网格中的项目及其编辑/新事件我必须在模型中显示一个带网格的模型 . 网格本身是另一个组成部分 .

除了网格之外,模型上有两个文本框,它们是父组件的一部分,它保存子组件(网格) . 在屏幕抓取之后,其中红色标记的是子组件 .

这是子组件选择器声明

@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);
    });
}

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

2 回答

  • 0

    在父组件上,您可以使用ViewChild指令

    @ViewChild('identifier') child: ChildType;

    在模板上,您为孩子添加了一个标识符

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

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

  • 0

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

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

    我习惯使用服务来处理这种交互 . 您可以在父级别创建服务,以便向子组件发送数据或从子组件接收数据,或者在子级别创建服务(如果它更有意义) .

    我可以为您提供几个例子,但我认为Angular文档总是有很好的例子 . 按照此link进行服务互动 .

相关问题