How can I communicate between Pipe and Component in Angular 2

1k Views Asked by At

 <tr *ngFor="let logDetails of logDetails | search : term" >

I have a Pipe in which I want to use a variable. Same variable has been defined in my Component. How can I pass this value from Component to Pipe?

//Pipe Structure

transform(value, [term], newVal) {
  if (value == undefined && newVal == undefined) {
    return undefined;
  } else {
    return value.filter((item) => item.LogString.startsWith(term));
  }
}

//Component Structure

newVal(a) {
  this.newChildData = a;
  console.log(this.newChildData);
}

I want to pass newChildData of Component into newVal of Pipe.

// HTML Template

1

There are 1 best solutions below

0
On

It's either you use the pipe in the template and pass new value into it.

<div>{{ yourValue | yourPipe: newChildData }}<div>

Or, since Pipe is just a Javascript class, you can import it in your component and use it.

const pipe = new youPipe();
const result = pipe.transform(yourValue, newChildData);

But I won't suggest the later.

If you want to use the pipe programmatically, consider splitting the transform logic to service, then import and use that service in both pipe and component.