Home > Software design >  Angular: Pass back real values from Subject
Angular: Pass back real values from Subject

Time:12-08

I have a Modal where the filters can be defined. After the modal is closed, the values will be processed like so:

modalRef.result.then((filters: Filter[]) => {
  this.filters$.next(filters);
});

filters$ is a BehaviorSubject<Filter[]>([]);

In the template I have the NgFor with a Pipe, which filters the rows. The filters will be resolved with the help of the async-pipe:

  <ul *ngIf="rows$ | async as rows">
    <li *ngFor="let row of rows | rowFilter: (filters$ | async)">
        ...
    </li>
  </ul>

If the filter modal gets opened again, I want to use the previous defined filters as the initial values. But exactly here is my problem. How to pass the Filters from the Subject to the filter modal?

At first I had something like that:

<button *ngIf="filters$ | async as filters" (click)="openFilterModal(filters)">Filter</button>

But then the button won't be displayed for the first time, when filters$ is [].

openFilterModal(filters: Filter[]): void {
    const modalRef = this.modalService.open(FilterComponent);
    modalRef.componentInstance.filters = filters;
}

My second approach was to use the subscribe() inside the openFilterModal() method, but that looks kinda odd to me:

openFilterModal(): void {
    const modalRef = this.modalService.open(FilterComponent);
    this.filters$.pipe(take(1)).subscribe(filters => {
        modalRef.componentInstance.filters = filters;
    }
}

CodePudding user response:

I would go with your second try tightly modyfied:

openFilterModal(): void {
    const modalRef = this.modalService.open(FilterComponent);
    modalRef.componentInstance.filters = this.filters$.value;
}
  • Related