Skip to content Skip to sidebar Skip to footer

Custom Structural Directive Inside Ngfor Updates Before Ngfor

I am creating a small application, which display a list of People with Name, Surname and Age fields using ngFor. The application has search field, where one can enter a query, and

Solution 1:

Instead of ngOnChanges approach you may try to apply BehaviorSubject approach . I'm not sure but Observable's .next() call should guarantee an additional event loop cycle which is necessary in your case as we can see per working zero setTimeout call.

import { Directive, Input, ElementRef, Renderer2 } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';

@Directive({
  selector: '[appQueryHighlight]'
})
export class QueryHighlightDirective {

  private _query = new BehaviorSubject<string>('');

  @Input('appQueryHighlight')
  set query(value: string) {
    this._query.next(value);
  };
  get query(): string {
    return this._query.getValue();
  }

  ngOnInit() {
    this._query.subscribe((query: string) => {
      // on query change handler
      // ... ngOnChanges-setTimeout previous code with 'query' instead of 'this.query'
    });
  }

}

Post a Comment for "Custom Structural Directive Inside Ngfor Updates Before Ngfor"