-
-
Save jorroll/888651f031b7736bfbac3a41afda1f4f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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