Angular如何将数据从子组件传递到父组件

9

我正在学习/工作于Angular项目,我已经做了很多事情并尝试以“正确的方式”去做,现在我想要做的是:

我想从子组件中获取变量(输出)到父组件,但我不想使用输出,也不想监听它,我想在父组件需要时获取它,类似于 child.getVariable()。我看到一篇帖子说我应该使用 childview,但问题与我的不同,所以我想知道是否使用 childview 从子组件获取数据是一个好的实践方法?


阅读文档 https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#parent-to-child-local-var - silentsod
可能是从父类调用子组件方法 - Angular 2的重复问题。 - silentsod
您可以查看此链接以获取详细解释:enter link description here - Rishi.S
你可以按照这里的指示操作。希望能对你有所帮助。 - Rishi.S
4个回答

4

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

Ref : stackoverflow.com/a/42109866/4697384


3
不要抄袭答案,引用它们: https://dev59.com/EVgQ5IYBdhLWcg3w3Xsy#42109866 - Charles Watson
这是从这里复制的答案 =>“https://dev59.com/EVgQ5IYBdhLWcg3w3Xsy”。 - WapShivam
我明确表示过我不想使用事件发射器,所以这个答案当时对我没有帮助。 - nikagar4

4

1
父组件如何与Angular中的子组件通信。
(i) 子组件通过公开一个 EventEmitter 属性来发出事件,当发生某些事情时就会触发事件。父组件绑定该事件属性并对这些事件做出反应。
(ii) 父组件无法使用数据绑定来读取子属性或调用子方法。您可以通过为子元素创建模板引用变量,然后在父模板中引用该变量来完成两者。
(iii) 本地变量方法简单易行。但是它的局限性在于父子关系必须完全在父模板内部完成。父组件本身无法访问子组件。
(iv) 父组件和子组件可以通过服务进行通信。
有关详细说明,请参阅以下链接: Angular官方网站-组件通信

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接