角度共享数据

时间:2020-06-29 07:08:25

标签: angular data-sharing

我有两个组成部分的父子关系。

我想在子组件中调用父组件方法。

我尝试了@Input装饰器,但这没用。

请帮助

2 个答案:

答案 0 :(得分:1)

父母监听孩子事件

子组件公开一个EventEmitter属性,当发生某些事件时,该属性将发出事件。父级绑定到该事件属性并对这些事件做出反应。

孩子的EventEmitter属性是一个输出属性,通常用@Output装饰装饰,如以下VoterComponent所示:

component-interaction/src/app/voter.component.ts

import { Component, EventEmitter, Input, Output } from '@angular/core';

@Component({
  selector: 'app-voter',
  template: `
    <h4>{{name}}</h4>
    <button (click)="vote(true)"  [disabled]="didVote">Agree</button>
    <button (click)="vote(false)" [disabled]="didVote">Disagree</button>
  `
})
export class VoterComponent {
  @Input()  name: string;
  @Output() voted = new EventEmitter<boolean>();
  didVote = false;

  vote(agreed: boolean) {
    this.voted.emit(agreed);
    this.didVote = true;
  }
}

点击按钮会触发发射布尔值有效载荷(true)或错误(false)。

父VoteTakerComponent绑定了一个名为onVoted()的事件处理程序,该事件处理程序响应子事件有效负载$ event并更新计数器。

component-interaction/src/app/votetaker.component.ts

import { Component }      from '@angular/core';

@Component({
  selector: 'app-vote-taker',
  template: `
    <h2>Should mankind colonize the Universe?</h2>
    <h3>Agree: {{agreed}}, Disagree: {{disagreed}}</h3>
    <app-voter *ngFor="let voter of voters"
      [name]="voter"
      (voted)="onVoted($event)">
    </app-voter>
  `
})
export class VoteTakerComponent {
  agreed = 0;
  disagreed = 0;
  voters = ['Narco', 'Celeritas', 'Bombasto'];

  onVoted(agreed: boolean) {
    agreed ? this.agreed++ : this.disagreed++;
  }
}

框架将事件参数(由$ event表示)传递给处理程序方法,然后该方法对其进行处理。

您应该阅读https://angular.io/guide/component-interaction上的完整指南

答案 1 :(得分:0)

@Input装饰器用于子组件从父组件获取数据。要从子组件的父组件调用方法,您有两个选择:

  1. 使用@Output装饰器和事件发射器将事件从子组件发射到父组件,在该事件上,您可以在父组件中调用方法。

    @Output() output: EventEmitter<any> = new EventEmitter<any>();

  2. 第二个选项是使用服务