我正在尝试在设定的时间后自动关闭NG Bootstrap alert。该警报已经具有我正在组件中使用的关闭事件。我正在添加其他超时功能作为指令,该指令应该能够触发close事件本身。像这样吗?
close-on-timeout.directive.ts
import { Directive, ElementRef, HostBinding, Input, OnInit } from '@angular/core';
@Directive({
selector: '[appCloseOnTimeout]'
})
export class CloseOnTimeoutDirective implements OnInit {
@Input() appCloseOnTimeout: number;
@HostBinding('close') close: CloseEvent;
constructor () {}
ngOnInit () {
setTimeout (() => this.close(), this.appCloseOnTimeout);
}
}
我希望能够使用这样的指令:
<ngb-alert
[dismissible]="alert.dismissible"
[type]="alert.type"
(close)="onClose(i)"
[appCloseOnTimeout]="1000"
>
访问主机元素的关闭事件的最佳方法是什么?我尝试使用ElementRef
代替,但仍然找不到访问事件的方法。
答案 0 :(得分:1)
使用类似...
import { Directive, ElementRef, HostBinding, Input, OnInit, Output, EventEmitter } from '@angular/core';
@Directive({
selector: '[appCloseOnTimeout]'
})
export class CloseOnTimeoutDirective implements OnInit {
@Input() appCloseOnTimeout: number;
@Output() close:EventEmitter<any> = new EventEmitter();
constructor () {}
ngOnInit () {
setTimeout (() => this.closeWrapp(), this.appCloseOnTimeout);
}
closeWrapp(){
this.close.emit()
}
}
答案 1 :(得分:0)
为什么不EventEmitter
?
import {
Directive,
ElementRef,
HostBinding,
Input,
OnInit,
Output,
EventEmitter
} from '@angular/core';
@Directive({
selector: '[appCloseOnTimeout]'
})
export class CloseOnTimeoutDirective implements OnInit {
@Input() appCloseOnTimeout: number;
@Output() close: EventEmitter = new EventEmitter();
constructor() {}
ngOnInit() {
setTimeout(() => this.onClose(), this.appCloseOnTimeout);
}
onClose() {
console.log('local close');
this.close.emit();
}
}