2017-05-28 73 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(需要包括在該HTML組分B)

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

parent.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函數中。如果有更好的方法,請諮詢。

+0

你可以創建一個plunker嗎? – Aravind

回答

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