I have a custom validator for blacklisting words from form controllers:
import { AbstractControl } from '@angular/forms';
const blacklist = ['poop'];
export function Blacklist(control: AbstractControl) {
let comment = control.value.split(' ');
for (let i = 0, j = comment.length; i < j; i++ ) {
if (blacklist.indexOf(comment[i]) !== -1) { // -1 = is no match in array
return {
validateBlacklist: {
blacklist: false
}
}
} else {
}
}
return null;
}
Everything works great! But when I try to do a validation message I get:
ERROR TypeError: Cannot read property 'validateBlacklist' of null
on every key up unless it's a word in my blacklist array...
From this:
<div *ngIf="commentForm.controls['newComment'].errors.validateBlacklist && commentForm.controls['newComment'].touched">Error</div>
What am I doing wrong?!
Error occurred due to ngIf condition.
Object
errors
doesn't havevalidateBlacklist
object at the time of check and it's current value is null. Tryconsole.log(this.commentForm.controls['newComment'].errors)
first.So it should look like this:
ngIf: