角元件的奇怪工作

时间:2017-07-03 09:52:01

标签: angular components counter

我对angular2并不了解。在简单的例子中,我正在尝试创建一个组件。代码如下:

import { Component, Input, Output, EventEmitter, ChangeDetectionStrategy } from '@angular/core';

@Component({
  selector: 'counter',
  templateUrl: './counter.component.html',
  styleUrls: ['./counter.component.css'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class CounterComponent {
  @Input()
  count: number;

  @Output()
  change: EventEmitter<number> = new EventEmitter<number>();

  increment() {
    this.count++;
    this.change.emit(this.count);
  }

  decrement() {
    if(this.count > 0)
    {
    this.count--;
    this.change.emit(this.count);
    }
  }

  reset()
  {
    this.count = 0;
    this.change.emit(this.count);
  }


  constructor()
  {

  }
}

模板代码:

<span>{{count}}</span>
<div>
  <button (click)="increment()">Increment</button>
  <button (click)="decrement()">Decrement</button>
  <button (click)="reset()">Reset</button>
</div>

我尝试使用此组件:

<counter [count]="5" (change)="countChange($event)"></counter>
<counter [count]="10" (change)="countChange($event)"></counter>

和“ts”

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app works!';
  countChange(event) {

  }
}

当我在浏览器中查看结果时,我看到第一个组件的计数字段是NaN,但是第二个组件的计数字段是正确且等于10.还增加,dicrement和重置事件仅适用于第二个组件。为什么以及我做错了什么?

0 个答案:

没有答案