如何在Angular 2中从子组件更新父组件

3
我希望在子组件更新时更新父组件。我试图使用事件发射器实现此目的,但是在调用子组件时使用了路由出口。我不知道该怎么做。
请问有什么方法可以实现这个功能吗?
谢谢。

1
请在此处发布您的代码 - Sajeetharan
我的回答解决了你的问题吗? - Adeeb basheer
请查看 https://angular.io/。 - Ajay
1个回答

5
你不能直接从子组件更新父组件。但你可以创建一个服务,可以从任何组件与任何其他组件进行交互,如下所示。
创建一个名为communication.service.ts的文件。
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';

@Injectable()
export class CommunicationService {
    constructor() { }

    private emitChangeSource = new Subject<any>();

    changeEmitted$ = this.emitChangeSource.asObservable();

    emitChange(data: {}) {
        this.emitChangeSource.next(data);
    }

}

在子组件中
import { Component } from '@angular/core';
import { CommunicationService } from './communication.service';

@Component({
    templateUrl: `./child.component.html`,
    styles: ['child.component.css']
})
export class ChildComponent{
    constructor(private _communicationService: CommunicationService) { }

    onSomething() {
        this._communicationService.emitChange({proprty: 'value'});
    }
}

在父组件中

import { Component } from '@angular/core';
import { CommunicationService } from './communication.service';

@Component({
    templateUrl: `./parent.component.html`,
    styles: ['./parent.component.css']
})

export class ParentComponent {    
    constructor( private _communicationService: CommunicationService ) { 
        _communicationService.changeEmitted$.subscribe(data => {
        // ...
        })
    }
}

感谢Adeeb的回答。我们能否使用相同的方法从父组件更新子组件? - Aakriti.G
当然可以这样做,但通常情况下您不需要这样做。您可以将子组件作为ViewChild,并更新其属性。 - Adeeb basheer

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