Angular input not triggering properly when using onPush

704 views Asked by At

I'm just getting started using ControlValueAccessor and so far I really like it but I'm at a problem I can't solve..

@Component({
  selector: 'app-project',
  templateUrl: './project.component.html',
  styleUrls: ['./project.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class ProjectComponent implements ControlValueAccessor, OnInit {

  @Input('companyNumber') set companyNumber(companyNumber: string) {
    this._companyNumber = companyNumber;
  }

  ctrlErrorStateMatcher = new CtrlErrorStateMatcher();
  private _companyNumber: string;

  constructor(
    private readonly _costCenterService: CostCenterService,
    @Optional() @Self() public ngControl: NgControl,

  ) {
    if (this.ngControl != null) {
      // Setting the value accessor directly (instead of using the providers) to avoid running into a circular import.
      this.ngControl.valueAccessor = this;
    }
  }

  onTouched = (_value?: any) => { };
  onChanged = (_value?: any) => { };

  writeValue(val: string): void {
    if (val) {
      this.ngControl.control?.setValue(val);
    }
  }

  registerOnChange(fn: any): void {
    this.onChanged = fn;
  }

  registerOnTouched(fn: any): void {
    this.onTouched = fn;
  }

  ngOnInit() {
    this.ngControl.control.setAsyncValidators(this.validate.bind(this));
    this.ngControl.control.updateValueAndValidity();
  }
  validate(control: AbstractControl): Observable<ValidationErrors | null> {
    const isValid = this._costCenterService
      .validateProject(control.value, this._companyNumber)
      .pipe(
        map(response => {
          return response ? null : { inValidProjectNumber: true };
        })
      );
    return isValid;
  }
}

export class CtrlErrorStateMatcher implements ErrorStateMatcher {
  isErrorState(control: FormControl): boolean {
    return !!(control && control.invalid);
  }
}

So this all works fine when I CHANGE the value in the input (not just triggering (blur) ).. but when the @Input changes it does not update the state (the validate() is triggered)...

if I then change the value in the input it does work... removing OnPush removes the issue but is not what I want to do..

Update: the template

<mat-form-field appearance="outline">
  <mat-label>Label</mat-label>
  <input matInput #projectInput [value]="ngControl.value" [formControl]="ngControl?.control"
    (change)=" onChanged($event.target.value)" (blur)="onTouched()" [errorStateMatcher]="ctrlErrorStateMatcher" />
  <mat-error *ngIf="ngControl.hasError('inValidProjectNumber')">
    Error
  </mat-error>
</mat-form-field>
1

There are 1 answers

0
Mackelito On BEST ANSWER

I found this git issue https://github.com/angular/angular/issues/12378

so for me the solution was to add a finalize pipe and use markForCheck()

  validate(control: AbstractControl): Observable<ValidationErrors | null> {
    const isValid = this._costCenterService
      .validateProject(control.value, this._companyNumber)
      .pipe(
        map(response => {
          return response ? null : { inValidProjectNumber: true };
        }),
        finalize(() => this.changeDetectorRef.markForCheck())
      );
    return isValid;
  }