5、绑定事件
基本用法
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: `
<button type="button" class="btn btn-primary" (click)="onClick()">Primary</button>
`,
styles: []
})
export class AppComponent {
onClick() {
console.log('onClick');
}
}
事件对象
$event就是原生的事件对象
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: `
<button type="button" class="btn btn-primary" (click)="onClick($event)">Primary</button>
`,
styles: []
})
export class AppComponent {
onClick(event: MouseEvent) {
console.log('onClick', event.target);
}
}
$event的类型
onKey(event: KeyboardEvent) { // with type info
this.values += (event.target as HTMLInputElement).value + ' | ';
}
ps:不是所有的event.target都有value属性,所有直接打印"event.target.value"就会报错,这时候我们需要给event.target指定明确的类型即可

浙公网安备 33010602011771号