在ngFor之前的ngFor更新中的自定义结构指令

时间:2018-01-14 01:21:39

标签: javascript angular typescript directive ngfor

我正在创建一个小应用程序,它使用ngFor显示名称,姓氏和年龄字段的人员列表。该应用程序具有搜索字段,可以输入查询,然后根据该查询将该列表替换为服务器中的新实体。

我创建了一个指令,用于突出显示ngFor行内查询的字母。

例如,如果我在数据库中有一个人,其名称是David,并且在我的查询中输入“Dav”,则只有包含“Dav”的实体将从ngFor中的服务器加载,而“Dav”字母将突出显示,“id”不会。如果我有David和Davin,两个实体都会突出显示。

该指令仅在我使用人工setTimeout()时才按预期工作,以确保在指令采取行动之前加载新列表。有没有其他方法可以使这项工作?

指令:

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

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

  @Input('appQueryHighlight') query: string;
  queryPos: number;
  paragraphElement: HTMLParagraphElement;

  constructor(private element: ElementRef, private renderer: Renderer2) {
    this.paragraphElement = (<HTMLParagraphElement>this.element.nativeElement);
  }

  ngOnChanges(changes: SimpleChanges){
    // Temporary timeout solution
    setTimeout(()=>{

      var childCount = this.paragraphElement.childElementCount;
      var text: string = "";

      // If paragraph contain SPANS, we need to flat them to innerHTML
      if(childCount > 1) {
        for(var i = 0; i < childCount; i++) {
          text += (<HTMLSpanElement>this.paragraphElement.childNodes[0]).innerHTML;
          console.log("SPAN" + (<HTMLSpanElement>this.paragraphElement.childNodes[0]).innerHTML);
          this.paragraphElement.removeChild(this.paragraphElement.childNodes[0]);
        }
        console.log("Text=" + text)
        this.paragraphElement.innerHTML = text;
      }

      console.log('Directive ngOnChanges: query=' + this.query + ", paragraph=" + this.paragraphElement.innerHTML);

      this.queryPos = this.paragraphElement.innerHTML.toUpperCase().indexOf(this.query.toUpperCase());
      if(this.query!="" && this.queryPos >= 0) {
        //this.paragraphElement.style.backgroundColor = 'yellow';

        //First span, containing pre-colored text
        var span1 = this.renderer.createElement('span');
        var text1 = this.renderer.createText(this.paragraphElement.innerHTML.substring(0,this.queryPos));
        this.renderer.appendChild(span1, text1);

        //Colored text span, containing query
        var span2 = this.renderer.createElement('span');
        var text2 = this.renderer.createText(this.paragraphElement.innerHTML.substr(this.queryPos, this.query.length));
        this.renderer.setStyle(span2, 'color', "red");
        this.renderer.setStyle(span2, 'text-decoration', "underline");
        this.renderer.appendChild(span2, text2);

        //Third span, containing text after query
        var span3 = this.renderer.createElement('span');
        var text3 = this.renderer.createText(this.paragraphElement.innerHTML.substring(this.queryPos + this.query.length));
        this.renderer.appendChild(span3, text3);

        this.paragraphElement.innerHTML = "";
        this.renderer.appendChild(this.paragraphElement, span1);
        this.renderer.appendChild(this.paragraphElement, span2);
        this.renderer.appendChild(this.paragraphElement, span3);
      }
      else {
        //this.paragraphElement.style.color = 'black';
      }
    }, 15);
  }
}

LIST-COMPONENT.TS:

ngOnChanges(changes: SimpleChanges) { 
  this.debtsService.getFilteredDebts(this.query)
    .subscribe(
      (data) => {
        this.debtsList = data;
        this.afterFilteringQuery = this.query;
      },
      (err) => console.log("Error occured: " + err)
    );
}

LIST-COMPONENT.HTML:

  <app-person-item 
    *ngFor="let person of personList;" 
    [query]="afterFilteringQuery">
  </app-person-item>

1 个答案:

答案 0 :(得分:0)

您可以尝试应用ngOnChanges方法,而不是BehaviorSubject方法。我不确定,但Observable的.next()调用应保证在您的情况下需要额外的事件循环周期,因为我们可以看到每个有效的setTimeout调用。

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'
    });
  }

}