Angular 2 Pipe条件下

Dan*_*cal 53 conditional-statements angular2-pipe angular-pipe angular

在Angular 2中是否可以在条件下应用管道?我想做的事情如下:

{{ variable.text | (variable.value ? SomePipe : OtherPipe) }}
Run Code Online (Sandbox Code Playgroud)

如果没有,实现这种效果的首选方法是什么?

Gün*_*uer 124

你需要稍微改变一下语法:

{{variable.value ? (variable.text | SomePipe) : (variable.text | pipe2)}}
Run Code Online (Sandbox Code Playgroud)

Plunker的例子

  • 谢谢@GünterZöchbauer`*ngFor ="让a(条件?(arr | pipe):( arr | pipe2))"` (3认同)

bvd*_*vdb 8

正如其他人指出的,您可以使用 的语法{{condition ? (value | pipe1) : (value2 | pipe2 )}}

但值得注意的是,管道的格式参数也可以是动态的。例如,这是可以以高精度或低精度格式化的数字的示例。该条件被传递给一个方法,该方法将有条件地创建格式化程序文本。

  // in template
  {{ value | number:getFormat(true) }}

  // in .ts
  public getFormat(highPrecision = false): string {
    const digits = highPrecision ? 3 : 2;
    return `1.${digits}-${digits}`;
  }
Run Code Online (Sandbox Code Playgroud)

所以,是的,您可以使用条件在 2 个管道之间进行选择。但在某些情况下,您可能更喜欢(或只需要)使用带有条件格式参数的一个管道。


ajo*_*era 7

你也可以使用ngIf

<span *ngIf="variable.value; else elseBlock">{{ variable.text | SomePipe }}</span>
<ng-template #elseBlock>{{ variable.text | OtherPipe }}</ng-template>
Run Code Online (Sandbox Code Playgroud)

我发现它在线路变得太长的情况下很有用。

  • 您可以将 &lt;span&gt; 替换为 &lt;ng-container&gt;,以便只有文本是有条件的,并且在第一种情况下不会包含任何标记。 (4认同)

Thi*_*ier 5

由于不支持这样的语法,我认为唯一的方法是实现另一个管道来处理这个条件:

@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);
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

并以这种方式使用它:

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

请参阅此plunkr:https://plnkr.co/edit/KPIA5ly515xZk4QZx4lp ? p = preview .

  • 在这种情况下,与其说是实际解决方案,不如说是一种解决方法,但对于更复杂的情况可能有用,+1 (2认同)