2017-05-28 21 views
0

コンポーネントAから親コンポーネントを介してコンポーネントBに情報を渡そうとしています。親コンポーネントを介した入力と出力の受け渡し

出力があるコンポーネントAを持っています。

componentA.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

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

parent.ts(このHTML中の成分Bを含む必要)

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

現在、コンポーネントAから渡された情報を表示できない「EventEmitter {_isScalar:false、observers:Array(0)、closed:false、isStopped:false、hasError:false ...」というメッセージが表示されます。 sがgetStatus関数内に存在することを確認します。より良いアプローチがある場合は、アドバイスをお願いします。

+0

プランナーを作成できますか? – Aravind

答えて

1

あなたの過ち、あなたが

以下のコードをフォローしngOnInitない変更を聞くためにngOnChangesを使用する必要がありますあなたの成分Bでthis.status.emit(..)

  • あるべき成分A、中

    • this.emit

      @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

  • 関連する問題