【问题标题】:How to update parent component from child component in Angular 2如何从Angular 2中的子组件更新父组件
【发布时间】:2018-01-01 05:53:45
【问题描述】:

我想在子组件更新时更新父组件。我试图使用事件发射器来实现这一点,但我正在使用路由器出口来调用子组件。我不知道该怎么做。

谁能指导我该怎么做才能得到这个?

谢谢

【问题讨论】:

  • 在此处发布您的代码
  • 我的回答解决了你的问题吗?
  • 检查angular.io

标签: angular angular-routing


【解决方案1】:

您不能直接从子组件更新父组件。但是您可以创建一个可以从任何组件与任何其他组件交互的服务,如下所示。

创建文件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 的回答。我们可以使用相同的方法从父组件更新子组件吗?
  • 当然..但通常你不需要这样做..你将孩子设为 ViewChild 并更新子属性
猜你喜欢
  • 2017-05-18
  • 2021-02-10
  • 2016-05-21
  • 2020-04-14
  • 2018-07-15
  • 2021-08-30
  • 2016-06-28
  • 2017-05-03
  • 2016-12-02
相关资源
最近更新 更多