【问题标题】:Angular pass data from child to parent从孩子到父母的角度传递数据
【发布时间】:2017-05-03 04:53:38
【问题描述】:

我正在学习/从事 Angular 项目,我已经做了很多,并且我尝试以“正确的方式”做事,所以现在我想做的是:

我想从子组件获取变量(输出)到父组件,但是我不想使用输出,我不想听它,我想在父需要时获取它,某事就像child.getVariable() 我遇到过一篇帖子说我应该使用childview,但问题和我的不一样,所以我想知道使用childview 从子组件获取数据是否是一种好习惯?

【问题讨论】:

标签: angular typescript output event-listener childviews


【解决方案1】:

您是否只需要从父模板中访问子组件的变量?如果是这样,您可以使用:

<child-component #childComponentRef></child-component>

然后您可以从您的父模板中访问#childComponentRef.someVariable。否则,我认为 Angular 团队推荐共享服务。无论如何,它们的用途更广。见https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#parent-and-children-communicate-via-a-service

【讨论】:

    【解决方案2】:

    将子组件中的 EventEmitter 注册为@Output:

    @Output() onDatePicked: EventEmitter<any> = new EventEmitter<any>();
    Emit value on click:
    
    public pickDate(date: any): void {
        this.onDatePicked.emit(date);
    }
    

    监听父组件模板中的事件:

    <div>
        <calendar (onDatePicked)="doSomething($event)"></calendar>
    </div>
    

    在父组件中:

    public doSomething(date: any):void {
        console.log('Picked date: ', date);
    }
    

    参考:stackoverflow.com/a/42109866/4697384

    【讨论】:

    【解决方案3】:

    如果您想同步访问子组件,那么使用 ViewChild 可能是一个好习惯,如下所示:

    import { CountryCodesComponent } from '../../components/country-codes/country-codes.component';
    import { Component, ViewChild } from '@angular/core';
    
    @Component({
        selector: 'signup',
        templateUrl: "signup.html"
    })
    export class SignupPage {
        @ViewChild(CountryCodesComponent)
        countryCodes: CountryCodesComponent;
        nationalPhoneNumber = '';
    
        constructor() {}
    
        get phoneNumber(): string {
            return '+' + this.countryCodes.countryCode + this.nationalPhoneNumber;
        }
    }
    

    【讨论】:

      【解决方案4】:

      在 Angular 中父组件与子组件通信的方式。

      (i) 子组件公开了一个 EventEmitter 属性,当事情发生时它会发出事件。父级绑定到该事件属性并对这些事件做出反应。

      (ii) 父组件不能使用数据绑定来读取子属性或调用子方法。您可以通过为子元素创建模板引用变量,然后在父模板中引用该变量来做到这两点

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

      (iv) 父母和孩子可以通过服务进行交流。

      详细解释可以参考以下链接:

      Angular Official website- Components communication

      【讨论】:

        猜你喜欢
        • 2018-06-05
        • 2018-10-02
        • 1970-01-01
        • 1970-01-01
        • 2020-06-17
        • 2021-10-16
        • 1970-01-01
        • 2018-06-29
        • 2021-10-31
        相关资源
        最近更新 更多