首页 文章

在评估为true之后删除ngIf属性

提问于
浏览
1

有没有办法如何删除ngIf属性后,它被evalauated为真?

例如,假设我有一个模板

<div class="container">
   <div *ngFor="let el of elements">
        <div *ngIf="el.index = index">
         ...
        </div>
   </div>
</div>

在组件中我有反击

class Test implements onInit{
   index = 0;

   ngOnInit(){
     setInterval( () => index++ )
   }
}

这意味着只会显示一个div,但是我希望以前显示的所有div保持显示,换句话说,一旦被评估为true,就删除ngIf属性 .

有可能吗?

谢谢

2 回答

  • 2

    这是不可能的 . 您应该维护组件中的元素列表以包含 *ngFor 应呈现的内容 .

  • 0

    您可以创建自己的ngIf:

    @Directive( { selector : '[myNgIf]' } )
    export class myNgIfDirective {
        private condition;
    
        constructor ( private templateRef : TemplateRef<any> ,
                      private viewContainer : ViewContainerRef ) {
        }
    
        @Input() set myNgIf ( condition : boolean ) {
            if ( this.condition !== true ) {
            // if this condition is once set to true , don't bother doing anything anymore 
                this.condition = condition;
                if ( condition ) {
                    this.viewContainer.createEmbeddedView( this.templateRef );
                } else {
                    this.viewContainer.clear();
                }
            }
        }
    }
    

    你可以用它:

    <div *myNgIf ="isTrue">stuff</div>
    

相关问题