Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 - Using pipe in (click) event

My question is probably simple but just can't find the way to use pipe within an event like (click) for example. Something like this:

<button (click)="quizAnswers(answer?.texte | translate | async)"></button>

I always get an error. I tried to wrap it with () or {} or []... There are some workaround like putting the content in an attribute and then get it on the event with this.attribute but I'm sure there is a proper way !

Thanks in advance for your help

like image 449
katzu Avatar asked Jul 30 '16 20:07

katzu


People also ask

Can we use 2 pipes in Angular?

Luckily, now these two pipes are not available in Angular 2 and instead Angular allows us to write custom pipes so we can write the custom pipes according to the logic we like to use.

Can we use pipe in TS file?

use date pipe in component ts files In laterst version of Angular i.e., from version 6 we can directly use angular pipes's public methods inside the components to format the values. For example we use date pipe format method formatMethod in component file by importing it from the @angular/common as shown below.

What does .pipe do in Angular?

The pipe's purpose is to allow the transformation of an existing value and reusability! Above, we have a pipe that computes age from a given date input. There are already built-in Angular pipes that we can use right away, like the date pipe and other custom pipes that you create for customized transformation.

How do you use custom pipes?

Steps Involved In Creating a Custom Pipe In Angular are: 1) Create a Pipe Class and decorate it with the decorator @Pipe. 2) Supply a name property to be used as template code name. 3) Register your Pipe in the module under declarations. 4) Finally, implement PipeTransform and write transformation logic.


2 Answers

I just got through this same issue. Action expressions can't contain the async pipe. However, you can use a hidden <input> element to hold the latest value of the promise/observable stream, and then access that value anywhere.

  <input #dummy style="{display: none}" type="text" value="{{ myAsyncSource | async }}">
  <a (click)="myFunction(dummy.value)">{{ dummy.value }}</a>

For your case of <button> there's actually a one-line solution that eliminates the need for the dummy <input>, posted in this solution:

 <button type="button" #item value="{{i$ | async}}"  (click)="buttonClicked(item.value)">BUTTON</button>
like image 135
Matthew Marichiba Avatar answered Oct 26 '22 10:10

Matthew Marichiba


A workaround would be to call your pipes in the click handler function instead:

function quizAnswers(answer)
{
    let translatePipe= new TranslatePipe();
    ...
    return translatePipe.transform(answer?.texte);
}
like image 6
null canvas Avatar answered Oct 26 '22 10:10

null canvas