我想创建一个按钮/链接的指令,在点击它时用加载器替换它的内部文本,并在调用成功或失败时重新设置其内部文本。
以下是我的开始:
HTML:
<button (click)="update()" asyncLoader >Update</button>
指令:
import {
Directive,
Input,
ElementRef,
AfterViewInit,
Output,
EventEmitter,
HostListener,
} from '@angular/core';
@Directive({
selector: '[asyncLoader]'
})
export class ActionAsyncLoader {
text: string;
// @Output() valueChanged = new EventEmitter();
constructor(private elementRef: ElementRef) {
}
ngOnInit(){
this.text = this.elementRef.nativeElement.innerHTML;
// console.log('this.text', this.text);
}
@HostListener('click', ['$event.target']) onClick(btn) {
console.log('click async btn', btn);
btn.innerHTML = 'Loading';
}
}
此处点击的元素将其文本替换为“正在加载&#39;。
”问题:由于在组件中设置了异步方法,如何从这里收听回调?
答案 0 :(得分:0)
现在,我只是在成功时发出一个事件而失败,然后在指令中对它进行处理......我在指令中传递一个输入以确保它与回调匹配。
HTML:
<button (click)="update()" asyncLoader='updateXYZ' >Update</button>
指令:
@Directive({
selector: '[asyncLoader]'
})
export class ActionAsyncLoader {
@Input('asyncLoader') asyncLoader: string;
text: string;
// @Output() valueChanged = new EventEmitter();
constructor(private elementRef: ElementRef,
private eventsService: EventsService) {
eventsService.onCallbackAsync.subscribe(obj => this.onCallbackAsync(obj));
}
ngOnInit(){
this.text = this.elementRef.nativeElement.innerHTML;
}
@HostListener('click', ['$event.target']) onClick(btn) {
btn.innerHTML = 'Loading';
}
onCallbackAsync(obj){
console.log('onCallbackAsync', obj);
// check if directive matches the callback event
if (this.asyncLoader === obj.asyncLoader){
this.elementRef.nativeElement.innerHTML = this.text;
}
}
}