如何将指令中的回调绑定到主机组件?
我正在与AngularFireAuth
合作
我已经创建了属性指令wich,该指令将附加到任何元素,并将接收输入作为回调函数。单击时,它将检查是否有登录用户,并且只有存在时,如果没有登录用户,请从currentUser
调用带有参数AngularFireAuth
的回调。
import { Directive, Input, HostListener, ViewContainerRef } from '@angular/core';
import { AngularFireAuth } from '@angular/fire/auth';
import { DialogService } from '../services/dialog.service';
@Directive({
selector: '[_persistance]'
})
export class PersistanceDirective {
@Input('_persistance') callback: Function;
constructor(
private fireAuth: AngularFireAuth,
private dialog: DialogService,
private viewRef: ViewContainerRef
) {}
@HostListener('click')onClick(){
const currentUser = this.fireAuth.auth.currentUser
if(currentUser){
const hostComponent = this.viewRef['_view'].component
this.callback.call(hostComponent,currentUser)
}else{
this.dialog.openSignIn()
}
}
}
所以我想在指令中绑定回调,而不是在模板中绑定
<button [_persistance]="someCallback.bind(this)"></button>
我尝试以viewRef['_view'].component
的身份访问主机组件,并且可以正常工作。但是有人认为这不是最佳实践,因为_view
是viewRef
的私有获取者,仅用于内部实现。