簡體   English   中英

角度表單自定義驗證器消息導致錯誤

[英]Angular form custom validator messages causing error

我有一個自定義驗證器,用於將表單控制器中的單詞列入黑名單:

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;
}

一切正常! 但是當我嘗試執行驗證消息時,我得到: ERROR TypeError: Cannot read property 'validateBlacklist' of null每個鍵上ERROR TypeError: Cannot read property 'validateBlacklist' of null除非它是我的黑名單數組中的一個單詞...

由此:

<div *ngIf="commentForm.controls['newComment'].errors.validateBlacklist && commentForm.controls['newComment'].touched">Error</div>

我究竟做錯了什么?!

由於ngIf條件而發生錯誤。

對象errors在檢查時沒有validateBlacklist對象,並且它的當前值為null。 首先嘗試console.log(this.commentForm.controls['newComment'].errors)

所以它應該看起來像這樣:

public isErrorOccurred(): boolean {
    if(
        'validateBlacklist' in this.commentForm.controls['newComment'].errors &&
        this.commentForm.controls['newComment'].touched
    ) {
        return 'blackList' in this.commentForm.controls['newComment'].errors.validateBlacklist;
    }
}

ngIf:

*ngIf="isErrorOccurred()"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM