Angular2: Passing values up from a component

2020-04-10 03:56发布

问题:

I'm really confused about how to pass a value back up to a parent component.

Here is some parent HTML that creates two child counter components

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

mchangetop is a little complicated in its instantiation but that's because I intend to make lots of change functions in due course.

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

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

Then the counter component itself has the following (you can see all the permutations I've tried).

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);
  }

};

As things stand, count is being passed down correctly, but I get errors about mchange not defined, which suggests change is wired up OK.

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

回答1:

You should initialize mchange with EventEmitter and use its next method. See 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