在Angular中,可以通过使用@Output
装饰器和EventEmitter
来实现从父组件向子组件发送确认事件。下面是一个示例:
父组件:
import { Component } from '@angular/core';
@Component({
selector: 'app-parent',
template: `
`
})
export class ParentComponent {
confirmationMessage: string;
onConfirm(confirmed: boolean) {
if (confirmed) {
console.log('子组件已确认');
} else {
console.log('子组件取消确认');
}
}
sendConfirmation() {
this.confirmationMessage = '确定要执行操作吗?';
}
}
子组件:
import { Component, Input, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-child',
template: `
{{ confirmationMessage }}
`
})
export class ChildComponent {
@Input() confirmationMessage: string;
@Output() confirm: EventEmitter = new EventEmitter();
constructor() { }
ngOnInit() {
}
confirm(confirmed: boolean) {
this.confirm.emit(confirmed);
}
}
在父组件中,我们定义了一个confirmationMessage
属性,并在sendConfirmation
方法中设置它的值。然后,我们通过在子组件的标签上使用(confirm)="onConfirm($event)"
来监听子组件的确认事件。
在子组件中,我们定义了一个confirmationMessage
输入属性,它接收来自父组件的确认消息。我们还定义了一个confirm
输出属性,并在confirm
方法中使用emit
方法来发送确认事件。
这样,当父组件中的按钮被点击时,确认消息会传递给子组件,并且子组件中的确认按钮被点击时会触发确认事件,父组件中的onConfirm
方法会根据子组件发送的确认结果进行相应的处理。