Angular 将ngIf属性求值为true后将其删除
有没有办法在ngIf属性被评估为true后删除它 例如,假设我有一个模板Angular 将ngIf属性求值为true后将其删除,angular,Angular,有没有办法在ngIf属性被评估为true后删除它 例如,假设我有一个模板 <div class="container"> <div *ngFor="let el of elements"> <div *ngIf="el.index = index"> ... </div> </div> </div> 这意味着一次只显示一个div,但是我希望以前显示的所有div都
<div class="container">
<div *ngFor="let el of elements">
<div *ngIf="el.index = index">
...
</div>
</div>
</div>
这意味着一次只显示一个div,但是我希望以前显示的所有div都保持显示状态,换句话说,一旦计算为true,就删除ngIf属性
这样可能吗
谢谢这是不可能的。您应该维护组件中的元素列表,以包含
*ngFor
应该呈现的内容。您可以创建自己的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();
}
}
}
}
@指令({选择器:'[myNgIf]})
导出类myNgIfDirective{
私人条件;
构造函数(私有templateRef:templateRef,
私有viewContainer:ViewContainerRef){
}
@Input()设置myNgIf(条件:布尔值){
if(this.condition!==true){
//如果这个条件一旦设置为true,就不要再费心做任何事情了
这个条件=条件;
如果(条件){
this.viewContainer.createEmbeddedView(this.templateRef);
}否则{
this.viewContainer.clear();
}
}
}
}
您可以使用它:
<div *myNgIf ="isTrue">stuff</div>
东西
当ngIf解析为true时,是否至少可以对函数求值?您可以使用类似的指令,但您的需求看起来更像是针对Angular2而不是使用它(除了您可能正在使用jQuery小部件)。我通过传递函数来解析它,该函数检查isViewed属性是否为true,如果是,则自动返回true。如果不是,则检查条件;如果条件为真,则设置为真
<div *myNgIf ="isTrue">stuff</div>