Angular 2 Pipe under condition

前端 未结 4 1971
醉梦人生
醉梦人生 2020-12-03 00:38

Is it possible in Angular 2 to apply a pipe under condition? I would like to do something like:

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


        
4条回答
  •  無奈伤痛
    2020-12-03 01:08

    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: `
        
    {{val | condition:cond:1}}
    `, pipes: [ Pipe1, Pipe2, ConditionPipe ] }) export class App { val:string = 'test'; cond:number = 1; }

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

提交回复
热议问题