2017-04-26 61 views
0

我想创建一个指令,删除/添加自己像* ngIf会做的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', 
    } 
}) 
... 

可悲的是,我不能在指令host使用'*ngIf': 'hidden'。我得到的错误是:

Can't bind to 'ngIf' since it isn't a known property of 'button'. 

'[ngIf]': 'hidden'不起作用。

那么,如何在指令中使用ngIf?

+3

指令不能动态添加/删除。 –

+0

Günter的评论^应该是被接受的答案 – balu

回答

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() { 
    } 
}