Get data from angular 2 pipe

2019-04-16 21:31发布

问题:

Is it possible to get filetered data from pipe to component?

If our data filtered by pipes in template, How I can grab this filtered data and pass it into my component ? :)

Many thanks for any help.

回答1:

I don't know if it's a good think and what is your exact use case but you can inject the component instance (or a shared service) into the pipe constructor.

Then you can set value on it:

@Pipe({
  name: 'test'
})
export class TestPipe {
  constructor(@Inject(forwardRef(() => AppComponent)) private comp:AppComponent) {

  }

  transform(value) {
    var filtered = value.map((v) => v-1);
    this.comp.filteredData = filtered;
    return filtered;
  }
}

See this plunkr: https://plnkr.co/edit/Lp6p97FtytdMM6mA7VGX?p=preview.