Angular 2 Pipe under condition

こ雲淡風輕ζ 提交于 2019-11-28 06:42:02

You need to change the syntax a bit:

{{variable.value ? (variable.text | SomePipe) : (variable.text | pipe2)}}

Plunker example

Since such syntax isn't supported, I think that the only way to do that is to implement another pipe to handle the condition:

@Pipe({
  name: 'condition'
})
export class ConditionPipe {
  transform(val,conditions) {
    let condition = conditions[0];
    let conditionValue = conditions[1];

    if (condition===conditionValue) {
      return new Pipe1().transform(val);
    } else {
      return new Pipe2().transform(val);
    }
  }
}

And use it this way:

@Component({
  selector: 'app'
  template: `
    <div>
      {{val | condition:cond:1}}<br/>
    </div>
  `,
  pipes: [ Pipe1, Pipe2, ConditionPipe ]
})
export class App {
  val:string = 'test';
  cond:number = 1;
}

See this plunkr: https://plnkr.co/edit/KPIA5ly515xZk4QZx4lp?p=preview.

You could also use ngIf

<span *ngIf="variable.value; else elseBlock">{{ variable.text | SomePipe }}</span>
<ng-template #elseBlock>{{ variable.text | OtherPipe }}</ng-template>

I find it useful in case the line becomes too long.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!