angularangular2-changedetection

What is the proper way to check multiple form values from the template in Angular?


There are a bunch of valid search combinations, and I want to disable the form unless a valid search fields have been entered. Currently I have a method isValidSearchCombo() I'm calling from the template, but I understand that is not best practice because change detection doesnt know when it needs to be re-run.

What is the best way to watch these fields and toggle a disableSearchButton boolean?

<button
  id="submit_button"
  type="submit"
  mat-flat-button
  [disabled]="!this.isValidSearchCombo()"
>
isValidSearchCombo(): boolean {
  return Boolean(
    this.searchForm.value.firstName
    && this.searchForm.value.lastName
    && this.searchForm.value.state
    || (this.searchForm.value.foo && (this.searchForm.value.bar || this.searchForm.value.fooBar))
    || (this.searchForm.value.barFoo)
  );
}

Solution

  • Since searchForm seems to be an Angular form, a change detection friendly version of that would be:

    isValidSearchCombo: boolean;
    
    ngOnInit(): void {
      this.searchForm.valueChange.subscribe((value) => {
        this.isValidSearchCombo = Boolean(
          value.firstName
          && value.lastName
          && value.state
          || (value.foo && (value.bar || value.fooBar))
          || (value.barFoo)
        );
      });
    }
    
    <button
      id="submit_button"
      type="submit"
      mat-flat-button
      [disabled]="!isValidSearchCombo">