对于url的示例:
http://ngcourse.rangle.io/handout/components/app_structure/two_way_data_binding.html
我无法理解以下两行如何针对@Output
运行//in app.component.ts
(countChange)="number2=$event"
(countChange)="onCountChanged($event)
//counter.component.ts
@Output() countChange: EventEmitter<number> = new EventEmitter<number>();
有人可以帮助连接点。
答案 0 :(得分:1)
this.countChange.emit('foo');
counter.component.ts
中的会调度一个事件
(有点类似于点击或其他DOM事件,但仅在内部处理Angular)
(countChange)="onCountChanged($event)
为此countChange
事件注册一个侦听器
这可能有点令人困惑,因为Angular使用与@Output()
相同的绑定语法和DOM事件。
执行this.countChange.emit('foo');
时,将调用已注册的事件处理程序并传递'foo'
(对于$event
参数)。
答案 1 :(得分:1)
简单来说,
要触发custom events
,我会使用EventEmitter
(通常从childcmp
到parentcmp
)。 @Output
是一种声明自定义事件名称(EventEmitter
的类型)的方法。
在您的情况下(来自 counter.component.ts ),
@Output() countChange: EventEmitter<number> = new EventEmitter<number>();
说countChange
是一个自定义事件(类型为EventEmitter
)。 EventEmitter
包含 emit(), next()等可以发出值的方法。所以这里说countChange
可以发出数值。例如
count=5;
buttonClick(){
this.countChange.emit(this.count); // will emit 5 value
}
请注意,EventEmitter
(此处countChange
)会发出任何(number
)值,自定义事件(通常在parentcmp
中使用)将由其自己触发。
在您的情况下(来自 app.component.ts ),
(countChange)="number2=$event" //number2=5; //countChange is a custom event
自动this.count
的 5 值将通过 $ event 收到,因此它将被分配到 number2 。这也适用于以下代码。
(countChange)="onCountChanged($event) //countChange is a custom event
用组件编写的某个地方。
onCountChanged(value)
{
console.log(value); // =5;
}