我有很多像这样的按钮:
<button (click)="func()">Press me!</button>
我想创建一个在执行func()
之前显示确认弹出窗口的指令。喜欢:
<button confirmModal (click)="func">Press me!</button>
我的确认模式的逻辑:
const confirmModal = this.modalService.open(ConfirmComponent);
confirmModal.result.then((result) => {
if (result === 'confirm') {
// execute func()
}
}, (reason) => {});
但我没有运气将它们混合在一起。不知何故需要制定指令,在执行func()
之前会显示弹出窗口。并且基于结果(true或false)将执行func()
[(click)bind]或不执行。任何想法怎么做?
答案 0 :(得分:2)
import { Directive, HostListener, Input } from '@angular/core';
@Directive({
selector: '[confirm]',
})
export class ConfirmDirective {
@Input() message: string;
@Input() onConfirm: Function;
@Input() onDismiss: Function;
@HostListener('click') onClick(e: Event) {
const confirmed = window.confirm(this.message);
if (confirmed && this.onConfirm) {
this.onConfirm();
}
if (!confirmed && this.onDismiss) {
this.onDismiss();
}
}
}
用法
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
template: `
<button confirm
[onConfirm]="onConfirm"
[onDismiss]="onDismiss"
[message]="'Are you sure?'">
Click me
</button>
`,
styleUrls: ['./app.component.css']
})
export class AppComponent {
onConfirm() {
console.log('confirmed');
}
onDismiss() {
console.log('dismissed');
}
}
我已将指令扩展为接受onConfirm
和onDismiss
回调函数,以使其更具可重用性。它们都是可选的。
请注意,[onConfirm]
不接受对回调函数(onConfirm
而非onConfirm()
)的引用。这同样适用于[onDismiss]
。