是否有方法将管道表达式的结果保存到变量中,以便在满足条件时使用?
<div class="mat-caption" *ngIf="(myDate | daysSinceSomeEvent) > 0">Days since event {{ myDate | daysSinceSomeEvent}}</div>
变成类似的东西
<div class="mat-caption" *ngIf="(myDate | daysSinceSomeEvent) as result > 0">Days since event {{result}}</div>
好吧,您总是可以通过组件的构造函数注入管道并使用它:
@Component({...})
export class YourComponent {
elapsedDays: number
private _yourDate: Date
@Input()
set yourDate(v: Date) {
this._yourDate = v;
this.elapsedDays = this.daysSinceSomeEvent.transform(v)
}
get yourDate(): Date {
return this._yourDate
}
constructor(private daysSinceSomeEvent: ElapsedTimePipe) {
}
}
如果您不打算将多个值作为输入传递,并将逻辑移动到ngOnInit
块中,那么您也可以取消属性getter和setter
然后在模板中只需使用elapsedDays
或result
变量
您可以将html包装在Ng容器中,该容器包含一个ngIf,该ngIf对结果进行别名以供重用。
<ng-container *ngIf=“(myDate | daysSinceSomeEvent) as result”>
<div class="mat-caption" *ngIf="result > 0">
Days since event {{result}}
</div>
<ng-container>