【发布时间】:2017-11-24 03:03:48
【问题描述】:
查看@input\@output 装饰器的一些代码,我发现了不同的行为。
在下面的代码中,有counter 组件通过@input 装饰器从父app 组件获取其值,并通过@output 装饰器发出更改。
我的问题:
当我在文本框中手动输入值时,为什么会调用更改事件?而我只在
Increment\Decrement函数中定义了this.change.emit(this.count);。 ?当我通过
Increment\Decrement按钮进行更改时,我在app组件(父级)中得到正确的更改值,但是当我手动输入值时,我得到@987654332 @ 未输入数字。为什么会这样?
代码在Plunker is here.下面
计数器组件:
import { Component, Input, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'counter',
template: `
<div class="counter">
<button (click)="decrement()">
Decrement
</button>
<input type="text" [(ngModel)]="count">
<button (click)="increment()">
Increment
</button>
</div>
`
export class CounterComponent {
@Input()
count: number = 0;
@Output()
change: EventEmitter<number> = new EventEmitter<number>();
increment() {
this.count++;
this.change.emit(this.count);
}
decrement() {
this.count--;
this.change.emit(this.count);
}
}
应用组件:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: `
<div class="app">
<counter
[count]="myCount"
(change)="countChange($event)">
</counter>
</div>
`
})
export class AppComponent {
myCount: number = 10;
countChange(event) {
console.log(event); //log Event object below
console.log('change called...!!!');
this.myCount = event;
}
}
我也尝试将输入类型更改为 number,还将绑定更改为 1 方式:[ngModel]="count",但似乎不起作用。
console.log(event);
事件 {isTrusted: true, type: "change", target: input.ng-untouched.ng-valid.ng-dirty,currentTarget:计数器, 事件阶段:3…}
【问题讨论】:
-
将事件名称替换为
change以外的名称。这是冒泡的标准事件plnkr.co/edit/kcRcSh8tAt4BMt81GvP0?p=preview -
@yurzui : 谢谢!!..,请发表您的评论作为答案,我会标记它..
标签: angular