我真的很困惑如何将值传递回父组件。
以下是一些创建两个子counter
组件
<div>
<h2>Counters</h2>
<counter [count]="model.top" (mchange)="mchangetop(delta)"></counter>
<counter [count]="model.bottom" (mchange)="mchangetop(delta)"></counter>
</div>
mchangetop
在实例化中有点复杂,但那是因为我打算在适当的时候做出很多改变功能。
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
答案 0 :(得分: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);
}
};