angular监听事件
时间: 2024-01-30 11:02:53 浏览: 249
在Angular中,可以使用以下两种方法来监听事件:
1. 使用@Output装饰器和EventEmitter类来创建自定义事件。在子组件中,使用EventEmitter类来触发自定义事件,然后在父组件中使用@Output装饰器来监听该事件。
例如,在子组件中定义一个名为myEvent的自定义事件:
```typescript
import { Component, EventEmitter, Output } from '@angular/core';
@Component({
selector: 'child-component',
template: '<button (click)="onClick()">Click me!</button>'
})
export class ChildComponent {
@Output() myEvent = new EventEmitter<string>();
onClick() {
this.myEvent.emit('Event triggered!');
}
}
```
然后在父组件中监听该事件:
```typescript
import { Component } from '@angular/core';
@Component({
selector: 'parent-component',
template: '<child-component (myEvent)="onMyEvent($event)"></child-component>'
})
export class ParentComponent {
onMyEvent(event: string) {
console.log(event);
}
}
```
2. 使用RxJS中的Subject类来创建可观察对象,然后在组件中订阅该可观察对象以监听事件。
例如,在组件中定义一个名为mySubject的Subject对象:
```typescript
import { Component } from '@angular/core';
import { Subject } from 'rxjs';
@Component({
selector: 'my-component',
template: '<button (click)="onClick()">Click me!</button>'
})
export class MyComponent {
mySubject = new Subject<string>();
onClick() {
this.mySubject.next('Event triggered!');
}
}
```
然后在组件中订阅该可观察对象以监听事件:
```typescript
import { Component } from '@angular/core';
import { MyComponent } from './my.component';
@Component({
selector: 'app-root',
template: '<my-component></my-component>'
})
export class AppComponent {
constructor(private myComponent: MyComponent) {
myComponent.mySubject.subscribe(event => console.log(event));
}
}
```
阅读全文