简体   繁体   English

我如何在Angular 2中的管道和组件之间进行通信

[英]How can I communicate between Pipe and Component in Angular 2

  <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? 如何将该值从Component传递到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. 我想将组件的newChildData传递到Pipe的newVal中。

// HTML Template // HTML模板

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. 或者,由于Pipe只是Javascript类,因此您可以将其导入组件中并使用它。

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 . 如果要以编程方式使用管道,请考虑将转换逻辑拆分为服务,然后在pipecomponent导入并使用该服务。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM