【问题标题】:Passing input and output through a parent component通过父组件传递输入和输出
【发布时间】:2017-10-28 16:06:53
【问题描述】:

我正在尝试将一些信息从组件 A 通过父组件传递到组件 B。

我有一个组件 A,我有输出。

组件A.ts

@Output() status = new EventEmitter();
public getColor() {
   ...
   this.emit(color);
}

componentB.ts

@Input('status') status;

ngOnInit() {
  console.log(this.status) // Got EventEmitter false object
}

parent.html(需要在这个HTML中包含组件B)

<componentA (status)="getStatus(s)"></componentA>
<componentB [status]="status"></componentB>

父.ts

@Output() status=new EventEmitter();
public getStatus(s) {
    this.status.emit(s)
}

目前我收到“EventEmitter {_isScalar: false,observers: Array(0), closed: false, isStopped: false, hasError: false...”消息,我无法查看从组件 A 传递的信息。我验证 s 是否存在于 getStatus 函数中。如果有更好的方法,请指教。

【问题讨论】:

  • 你能创建一个 plunker 吗?

标签: angular typescript components eventemitter


【解决方案1】:

你的错误,

  • this.emit 在组件 A 中,应该是 this.status.emit(..)
  • 在您的组件 B 中,您应该使用 ngOnChanges 而不是 ngOnInit 来监听更改

按照下面的代码,

@Component({
  selector: 'my-app',
  template: `
    <div> 
      {{status}}
      <componentA (status)="getStatus($event)"></componentA>
    <componentB [status]="status"></componentB>
    </div>
  `,
})
export class App {
  name:string;
  status:string;
  getStatus(event){
    console.log(event)
    this.status = event
  }
  constructor() {

  }
}
@Component({
  selector: 'componentA',
  template: `
    <div>
     <button (click)="getColor()"> Click for red color</button>


    </div>
  `,
})
export class CompA {
  @Output() status = new EventEmitter<string>();
  public getColor() {
     this.status.emit('red');
}
}
@Component({
  selector: 'componentB',
  template: `
    <div>

    </div>
  `,
})
export class CompB {
  @Input('status') status;
  ngOnChanges() {
  console.log('CompB input arrived', this.status) // Got EventEmitter false object
}
}

LIVE DEMO

【讨论】:

    猜你喜欢
    • 2016-12-09
    • 2018-03-08
    • 1970-01-01
    • 1970-01-01
    • 2021-03-21
    • 2017-05-29
    • 2021-05-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多