I want to create a Directive that removes/adds itself to the DOM like *ngIf would do. What i have so far is:
@Directive({
selector: '[myDirective]',
host: {
'[hidden]': 'hidden',
}
})
export class MyDirective {
constructor(private myService : MyService) {
}
hidden() {
return !this.myService.valid;
}
But what i need is something like:
@Directive({
selector: '[myDirective]',
host: {
'*ngIf': 'hidden',
}
})
...
Sadly i can not use '*ngIf': 'hidden' in host of Directive. The error i get is:
Can't bind to 'ngIf' since it isn't a known property of 'button'.
Also '[ngIf]': 'hidden' is not working.
So, how can i use ngIf in a Directive?
@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() {
}
}