Angular 2 Pipe under condition

前端 未结 4 2030
醉梦人生
醉梦人生 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:01

    As others pointed out, you can use the syntax of {{condition ? (value | pipe1) : (value2 | pipe2 )}}.

    But it is worth knowing that also the format parameter of a pipe can be dynamic. e.g. this is an example of a number which can be formatted with a high precision or a low precision. The condition is passed to a method, which will create a formatter text conditionally.

      // in template
      {{ value | number:getFormat(true) }}
    
      // in .ts
      public getFormat(highPrecision = false): string {
        const digits = highPrecision ? 3 : 2;
        return `1.${digits}-${digits}`;
      }
    

    So, yes, you can use a condition to select between 2 pipes. But in some cases you may prefer (or only need) to use one pipe with a conditional format parameter..

提交回复
热议问题