gpt4 book ai didi

Angular 2 : Passing values up from a component

转载 作者:太空狗 更新时间:2023-10-29 18:27:19 25 4
gpt4 key购买 nike

我真的很困惑如何将值传回父组件。

这是一些创建两个子 counter 组件的父 HTML

<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 not defined 的错误,这表明 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

最佳答案

您应该使用 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);
}
};

关于 Angular 2 : Passing values up from a component,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33220451/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com