我想创建一个指令,删除/添加到DOM,就像* ngIf那样。到目前为止我所拥有的是:
@Directive({
selector: '[myDirective]',
host: {
'[hidden]': 'hidden',
}
})
export class MyDirective {
constructor(private myService : MyService) {
}
hidden() {
return !this.myService.valid;
}
但我需要的是:
@Directive({
selector: '[myDirective]',
host: {
'*ngIf': 'hidden',
}
})
...
遗憾的是,我无法在'*ngIf': 'hidden'
指令中使用host
。我得到的错误是:
Can't bind to 'ngIf' since it isn't a known property of 'button'.
此外'[ngIf]': 'hidden'
无效。
那么,我如何在指令中使用ngIf?
答案 0 :(得分:0)
@Injectable()
export class MyService {
valid = true;
}
@Directive({
selector: '[myIf]'
})
export class MyIfDirective {
constructor(private myService: MyService,
private el:ElementRef,
private view:ViewContainerRef,
private template:TemplateRef<any>) {
}
ngAfterViewInit(){
if(this.myService.valid) {
this.view.createEmbeddedView(this.template);
}
}
}
@Component({
selector: 'my-app',
template: `
<div>
Peek A Boo: <h2 *myIf>Hello</h2>
</div>
`,
})
export class App {
constructor() {
}
}