角度2管状态

在这种情况下,在角度2下是否可以使用管道? 我想做这样的事情:

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

如果没有,那么达到这种效果的首选方法是什么?

72380 次浏览

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 need to change the syntax a bit:

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

Plunker example

You could also use ngIf

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

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

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..