在Angular中使用@Output装饰器和EventEmitter来创建可订阅的事件是很常见的。下面是一个示例代码,演示了如何在父组件中订阅子组件发出的事件。
父组件:
import { Component } from '@angular/core';
@Component({
selector: 'app-parent',
template: `
Last custom event value: {{ lastEventValue }}
`
})
export class ParentComponent {
lastEventValue: string;
onCustomEvent(event: string) {
this.lastEventValue = event;
}
}
子组件:
import { Component, EventEmitter, Output } from '@angular/core';
@Component({
selector: 'app-child',
template: `
`
})
export class ChildComponent {
@Output() customEvent = new EventEmitter();
onClick() {
this.customEvent.emit('Custom event emitted from child component');
}
}
在父组件的模板中,通过在子组件标签上使用(customEvent)="onCustomEvent($event)"
来订阅子组件发出的事件。当子组件中的按钮被点击时,会触发onClick()
方法,该方法会发出一个自定义事件,并将事件的值作为参数传递给this.customEvent.emit()
方法。父组件中的onCustomEvent()
方法会接收到这个事件,并将事件的值保存到lastEventValue
属性中。最后,可以在父组件的模板中使用{{ lastEventValue }}
来显示最后一个自定义事件的值。
注意:父组件需要在其模板中引入子组件,例如
,以便子组件能够被显示和使用。