2015-10-19 86 views
2

對於如何將值傳遞迴父組件,我感到非常困惑。Angular2:從組件向上傳遞值

下面是創建兩個子counter組件

<div> 
    <h2>Counters</h2> 
    <counter [count]="model.top" (mchange)="mchangetop(delta)"></counter> 
    <counter [count]="model.bottom" (mchange)="mchangetop(delta)"></counter> 
</div> 

mchangetop在其實例有點複雜,但是那是因爲我打算做很多的變化功能在適當的時候一些家長HTML。

mchangetop(delta) { 
    this.mchange('top')(delta); 
} 

mchange(countName){ 
    return (delta => this.model[countName] += delta); 
} 

然後counter組件本身也有以下的(你可以看到所有我試着排列)。

import { Component, View } from 'angular2/angular2'; 

@Component({ 
    selector: 'counter' 
    , properties: ['count:count', 'mchange:mchange'] 
}) 
@View({ 
    templateUrl: 'app/components/counter/counter.html', 
}) 
export class CounterComponent { 
    // @Input() count : Number; 
    // @Output() mchange : Function; 

    // count: Number; 
    // mchange: Function; 

    constructor() { 
    // this.count = count; // count gets set up correctly 
    } 

    change(delta) { 
    this.mchange(delta); 
    } 

}; 

就目前情況來看,count被正確地傳遞下去,但我得到mchange錯誤沒有定義,這表明change連線了確定。

EXCEPTION: Error during evaluation of 
"click"BrowserDomAdapter.logError @ 
angular2.dev.js:21835BrowserDomAdapter.logGroup @ 
angular2.dev.js:21846ExceptionHandler.call @ 
angular2.dev.js:4431(anonymous function) @ 
angular2.dev.js:19543NgZone._onError @  
angular2.dev.js:10711errorHandling.onError @ angular2.dev.js:10630run @ 
angular2.dev.js:141(anonymous function) @ 
angular2.dev.js:10644NgZone.run @ angular2.dev.js:10607outsideHandler 
@ angular2.dev.js:17809run @ angular2.dev.js:138zoneBoundFn @  
angular2.dev.js:111 
angular2.dev.js:21835 ORIGINAL EXCEPTION: ReferenceError: mchange is not defined 

回答

3

你應該EventEmitter初始化mchange並利用其next方法。見this plunker

import {Component, View, Input, Output, EventEmitter} from 'angular2/angular2' 

@Component({ 
    selector: 'counter' 
}) 
@View({ 
    template: ` 
    <h1 (click)="change(10)">Count {{ count }}</h1> 
    `, 
}) 
export class Counter { 
    @Input() count : Number; 
    @Output() mchange = new EventEmitter(); 

    change(delta) { 
    this.mchange.next(delta); 
    } 
}; 
+1

這不完全直觀,但謝謝! –

相關問題