角度通过从孩子到父母的数据



我正在学习/在Angular项目上工作,我已经做了很多事情,我尝试做"正确的方式",所以现在我想做的是:

我想从子组件到父零件,但我不想使用输出,我不想听它,我想在父母需要时得到它,像child.getVariable()一样,我遇到了一篇文章,该帖子说我应该使用Childview,但问题与我的问题不一样,所以我想知道使用Childview是否从Child Component获取数据是一个好习惯吗?

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

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

然后,您可以从您的父模板内访问#ChildComponentRef.somevaria。否则,我认为Angular团队建议共享服务。无论如何它们都有更多的用途。请参阅https://angular.io/docs/ts/latest/cookbook/component-communication.html# !! #parent-and-communicate-communicate-via-a-a-service

在您的孩子组件中注册@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

如果要同步访问子组件,那么最好使用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;
    }
}

父母如何与Angular中的子分量进行交流。

(i)儿童组件公开了 eventEmitter 属性在发生某些事情时会发出事件的属性。父母与该事件属性结合并对这些事件做出反应。

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

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

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

有关详细说明,您可以参考以下链接:

Angular官方网站 - 组件通信

最新更新