Skip to content

Instantly share code, notes, and snippets.

@dcagnetta
Created September 14, 2022 13:23
Show Gist options
  • Select an option

  • Save dcagnetta/d50e12bf6a06ef12ade0ea8dafb3cf26 to your computer and use it in GitHub Desktop.

Select an option

Save dcagnetta/d50e12bf6a06ef12ade0ea8dafb3cf26 to your computer and use it in GitHub Desktop.

Revisions

  1. @dillancagnetta dillancagnetta created this gist Sep 14, 2022.
    37 changes: 37 additions & 0 deletions gistfile1.txt
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,37 @@
    this.form = this.formBuilder.group({
    code: ['',
    [Validators.required, Validators.pattern('^[A-Za-z0-9]{4}')],
    this.asyncCodeValidator.validate(),
    ]
    });


    @Injectable({ providedIn: 'root' })
    export class AsyncCodeValidatorService {
    constructor(private codeService: CampaignService) {}

    validate(): AsyncValidatorFn {
    return (control: AbstractControl): Observable<ValidationErrors | null> => {
    return this.searchCode(control.value).pipe(
    map(result => {
    return result.available ? null : { notUnique: 'Action code not unique' };
    })
    );
    };
    }

    searcCode(code: string): Observable<CodeValidate> {
    return timer(500).pipe(
    switchMap(() => {
    return this.codeService.validateCode(code); // return Observable<CodeValidate>
    })
    );
    }


    <form [formGroup]="form">
    <input type="text" formControlName="code">

    <p style="color: red" *ngIf="form.get('code').errors?.notUnique">code not available</p>
    </form>
    }
    5 changes: 5 additions & 0 deletions gistfile2.txt
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,5 @@
    https://stackoverflow.com/questions/68034096/angular-asyncvalidatorfn-works-only-onblur-and-not-on-keypress-event

    Not updateding in the DOM

    remove: changeDetection: ChangeDetectionStrategy.OnPush