typescript - Angular: setErrors nezobrazuje správu


Snažím sa zobraziť nastavenú chybovú správu vo svojom vlastnom ovládacom prvku, ale bez úspechu..správa je vždy prázdna! Čo mi chýba? onSelectedCC(event: any)//toto sa volá na zapnutie/vypnutie overovača telefónu

HTML

<div class="form-group col-xs-3 col-md-3"
                                     [ngClass]="{
                                     'has-error':(ersaForm.get('phone').touched || ersaForm.get('phone').dirty ) &&
                                     !ersaForm.get('phone').valid
                                     }">

                                    <label for="phoneLabel" class="control-label">Phone</label>


                                    <input type="tel" formControlName="phone" pattern="^[0-9-+s()]*$" class="form-control" id="phoneLabel"   placeholder="Phone">

                                    <span class="help-block" *ngIf="(ersaForm.get('phone').touched || ersaForm.get('phone').dirty ) &&
                                     ersaForm.get('phone').errors">
                                        <span *ngIf="ersaForm.get('phone').errors.customVal">
                                            <!--Phone Number does not exist.-->
                                        </span>

                                    </span>

TS(vlastná kontrola funguje, ale správa je prázdna)

return (c: AbstractControl): { [key: string]: boolean } | null => {

        let dataForm = c.parent;
        c.setErrors(null);
         var phoneVal = "";
        if (c.value.length != 10) {    
            c.setErrors({ 'incorrect phone format': true });

            return { 'customVal': true };
        }


        if (c.value != undefined && val == -1 && val != '') {
            c.setErrors({ 'Phone Number does not exist.': true });
            return { 'customVal': true };
        };
        return null;
    };
}       

    this.ersaForm = this._fb.group({
        phone: '',

    });

onSelectedCC(event: any)//this called to turn on/off phone validator
{
    const phoneControl = this.ersaForm.get('phone');

    let cc = event.value.name;
    if (cc == '1111' )
    {
        phoneControl.setValidators([Validators.required, phoneCheck(this.customVal)]);
                }
    else {
        phoneControl.clearValidators();

    }
    phoneControl.updateValueAndValidity();
}

Odpoveď č. 1

Vyzerá to, že text vašej chybovej správy je zakomentovaný:

<!--Phone Number does not exist.-->

Skús toto:

<span class="help-block" *ngIf="(ersaForm.get('phone').touched || ersaForm.get('phone').dirty ) && ersaForm.get('phone').invalid">
   <span *ngIf="ersaForm.get('phone').hasError('customVal')">
       Phone Number does not exist
   </span>
</span>

Odpoveď č. 2

aby sa chyba zobrazila na poli bez rozmazania, stačí pridať markAsTouched :

c.get('end').setErrors({ invalid: true });
c.get('end').markAsTouched({ onlySelf: true });

Súvisiace články