Skip to content

Instantly share code, notes, and snippets.

@jorroll
Created November 4, 2019 22:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jorroll/888651f031b7736bfbac3a41afda1f4f to your computer and use it in GitHub Desktop.
Save jorroll/888651f031b7736bfbac3a41afda1f4f to your computer and use it in GitHub Desktop.
@Component({
selector: 'app-email-address-input',
template: `
<div>
<label>Email address</label>
<input [formControl]="control" [required]="required" />
</div>
`,
providers: [
{
provide: NG_CONTROL_ACCESSOR,
useExisting: forwardRef(() => FirstNameInputComponent),
multi: true,
},
],
})
export class FirstNameInputComponent implements ControlAccessor {
@Input() required = false;
readonly control = new FormControl('');
private subscriptions: Subscription[] = [];
constructor(private userService: UserService) {}
ngOnInit() {
this.subscriptions.push(
this.control.validationEvents
.pipe(
filter(event => event.label === 'End'),
tap(() =>
this.control.markPending(this.control.valid, {
source: 'emailValidator',
}),
),
switchMap(event => {
// if the control is already invalid,
// don't bother with async validation
if (this.control.invalid) return NEVER;
return interval(1000).pipe(
take(1),
switchMap(() => this.userService.findUserByEmail(event.controlValue)),
map(user => !!user),
);
}),
tap(() =>
this.control.markPending(false, { source: 'emailValidator' }),
),
)
.subscribe(userExists => {
const error = userExists
? { userExists: 'Email address taken' }
: null;
this.control.setErrors(error, {
source: 'emailValidator',
});
}),
);
}
ngOnDestroy() {
this.subscriptions.forEach(sub => sub.unsubscribe());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment