Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to exclude a special case from a directive behavior?

I am trying to fix a bug that I'm getting while searching on my page. I have a component to search in all of my settings, like this:

Search settings component

Everything is working fine, the search is returning the values it is supposed to, but when I remove the search criteria, I note that the first letter of the criteria is still showing and does not disappear, even when the search settings field is empty, just like this:

Avatar string with A selected

After two hours of checking at the code, I can see where in the code is the problem, but I don't know how to fix it.

This is my component's html:

<mat-form-field appearance="standard">
      <input matInput
             pageSearch
             placeholder="{{'searchSettings'|translate}}">
    </mat-form-field>

As you can see, I am using a directive called pageSearch that is defined as follows and contains a method valueChange that executes each time a keyboard key is released:

ngAfterViewInit() {
    const subscription = this.router.events
      .pipe(filter(e => e instanceof NavigationStart))
      .subscribe(event => {
          if (event) {
            this.pageSearchService.term.next('');
          }
        }
      );
    this.subscriptionsManager.add(subscription);
  }

@HostListener('keyup')
  valueChange() {
    this.pageSearchService.term.next(
      this.elementRef.nativeElement.value
    );
  }

This directive uses the pageSearchService, defined as follows:

@Injectable()
export class PageSearchService {
  /**
   * Current search term.
   */
  term: BehaviorSubject<string>;
  /**
   * Event to emit when visibility should change in the searchable.
   */
  searchableMatch: EventEmitter<any> = new EventEmitter<any>();

  constructor() {
    this.term = new BehaviorSubject('');
  }
}

I have a slight idea that the problem might be that it is always expecting a next() value, and when it is null, it just does not run, but the last value it had is still frozen in there.

I have tried changing the method valueChange in the directive, but every time I end up closing the subscription to the BehaviorSubject. These are the things I have tried:

  1. Add a condition to check if the string is empty and not to call the BehaviorSubject
valueChange() {
    if (this.elementRef.nativeElement.value !== '') {
      this.pageSearchService.term.next(
        this.elementRef.nativeElement.value
      );
    }
  }

It did not work, I also tried to unsubscribe and subscribe again, but it did not worked either

valueChange() {
    if (this.elementRef.nativeElement.value !== '') {
      this.pageSearchService.term.next(
        this.elementRef.nativeElement.value
      );
    } else {
      this.pageSearchService.term.unsubscribe();
      this.pageSearchService.term._subscribe(this.elementRef.nativeElement.value);
    }
  }

It is giving me this error:

Error when unsubscribing

So now I do not know what else to do. How can I ask the directive not to behave a certain way given the string ''?

The searchableMatch EventEmitter is used by other 3 directives, as follows:

The SearchNoResultsDirective:

export class SearchNoResultsDirective implements AfterViewInit, OnDestroy {
  @Input('searchNoResults') sectionsId: string[];
  subscriptionsManager: Subscription = new Subscription();
  visibility: {
    term: string,
    visible: boolean
  } = {
    term: '',
    visible: true
  };

  constructor(private elementRef: ElementRef,
              private renderer: Renderer2,
              private pageSearchService: PageSearchService) {
  }

.
.
.

  ngAfterViewInit() {
    const subscription = this.pageSearchService.searchableMatch.subscribe(match => {
      if (this.sectionsId.indexOf(match.sectionId) >= 0 ) {
        this.update({
          term: match.term,
          visible: match.visible
        });
      }
    });
    this.subscriptionsManager.add(subscription);
  }
}

The SearchableSectionDirective:

export class SearchableSectionDirective extends BaseClass implements AfterViewInit {
  @Input('searchableSection') sectionId: string;

.
.
.

  ngAfterViewInit() {
    const subscription = this.pageSearchService.searchableMatch.subscribe(match => {
      if (match.sectionId === this.sectionId) {
        this.update({
          term: match.term,
          visible: match.visible
        });
      }
    });
    this.subscriptionsManager.add(subscription);
  }
}

And the SearchableDirective:

export class SearchableDirective implements AfterViewInit, OnDestroy {
  @Input('searchable') sectionId: string;
  @Input() highlightColor = '#FFF176';
  match: EventEmitter<any> = new EventEmitter<any>();
  subscriptionsManager: Subscription = new Subscription();
  originalText: string;

  ngAfterViewInit() {
    this.originalText = this.elementRef.nativeElement.innerText;
    this.subscriptionsManager.add(
      this.pageSearchService.term.subscribe(term => this.checkIfMatch(term))
    );
  }

  checkIfMatch(val: string) {
    let match = false;
    let clean = false;
    if (val) {
      const startInd = this.originalText.toLowerCase().indexOf(val.trim().toLowerCase());
      if (startInd > -1) {
        match = true;
        const startText = this.render.createText(this.originalText.slice(0, startInd));
        const matchText = this.render.createText(this.originalText.slice(startInd, startInd + val.trim().length));
        const endText = this.render.createText(this.originalText.slice(startInd + val.trim().length, this.originalText.length));

        const matchSpan = this.render.createElement('span');
        this.render.appendChild(
          matchSpan,
          matchText
        );
        this.render.setStyle(
          matchSpan,
          'background',
          this.highlightColor
        );

        this.elementRef.nativeElement.innerHTML = '';

        this.render.appendChild(
          this.elementRef.nativeElement,
          startText
        );
        this.render.appendChild(
          this.elementRef.nativeElement,
          matchSpan
        );
        this.render.appendChild(
          this.elementRef.nativeElement,
          endText
        );
      } else {
        clean = true;
      }
    } else if (this.originalText) {
      clean = true;
    }

    **if (clean) {
      // this is how the solution looks
      this.elementRef.nativeElement.innerHTML = this.originalText;
    }**

    if (this.sectionId) {
      this.pageSearchService.searchableMatch.emit({
        sectionId: this.sectionId,
        term: val,
        visible: match
      });

      this.match.emit({
        term: val,
        visible: match
      });
    }
  }
}

I am looking through these 3 directives to see if I find the problem.

like image 348
Dairelys García Rivas Avatar asked Nov 06 '22 11:11

Dairelys García Rivas


1 Answers

I think the only problem is the function where you have putted the logic. I think you need to only add in checkIfMatch

checkIfMatch(val: string) {

    let match = false;
    let clean = false;
    if (val) {

       //func logic

     } else {
        // you need to add else block to the function
        this.elementRef.nativeElement.innerHTML = this.originalText;

     }

}

like image 181
Ashot Aleqsanyan Avatar answered Nov 15 '22 05:11

Ashot Aleqsanyan