Подтвердить что ты не робот

Angular Абстрактное управление удаляет ошибку

Я хочу, чтобы удалить определенную ошибку из элемента управления формой и не очистить всю ошибку.

control.setError({'firstError': true})

и удалить эту конкретную ошибку, например

control.removeError({'firstError}) and not control.setError({null})

Я пробовал

control.setError({'firstError': false})

но не работает.

Любая помощь. Благодаря

angular 4.1.1

4b9b3361

Ответ 1

Вы можете удалить вот так:

control.setError({'firstError': null})

Ответ 2

Вы можете удалить ошибку с помощью:

control.setError({'firstError': null});

control.updateValueAndValidity();

Ответ 3

Во-первых, вы должны проверить ваше поле на наличие этой ошибки. Затем удалите это. И для завершения вам необходимо обновить все ошибки в вашем контроле.

Примерно так в функции валидатора:

if (control.hasError('firstError')) {
      delete control.errors['firstError'];
      control.updateValueAndValidity();
    }

уважением.

Ответ 4

К сожалению, это не сработало для меня. Я просто использовал updateValueAndValidity(), который используется для пересчета значения и проверки. Ниже приведена моя функция валидатора, которая проверяет мои grossWeight.

validateWeights(formGroup) {
    let netWeight = formGroup.get('netWeight');
    let grossWeight = formGroup.get('grossWeight');

    if (parseFloat(netWeight.value) > parseFloat(grossWeight.value)) {
        grossWeight.setErrors({ 'customError': true });
        netWeight.setErrors({ 'customError': true });
    } else {
        if(netWeight.errors && netWeight.errors['customError']) {
            netWeight.updateValueAndValidity();
        }
        if (grossWeight.errors && grossWeight.errors['customError']) {
            grossWeight.updateValueAndValidity();
        }
    } 
}

Ответ 5

Если мы добавляем и удаляем ошибки динамически, начиная с Angular 8, приведенные выше примеры просто не работают. Я добавляю ошибки в зависимости от состояния других элементов управления. у меня два клиента определены с одним и тем же адресом электронной почты. Это единственное решение, которое я смог найти.

tap(duplicateError => {
    /* Note to future self...
     * I'm beginning to hate AbstractControl.errors.
     * The email control can have multiple errors (required, email, and duplicate);
     * The ONLY way to clear an error is to not have it in the object that is passed to the setErrors call.
     * You CANNOT pass null or undefined! It will still be evaluated as an error!
     * This is also true if there are NO errors AT ALL. You cannot pass setErrors({}) or the control will be
     * invalid, even though there are no errors! You must call setErrors(null);
     * This is stupid, but it the only way it works.
     * This code is concerned with setting/removing the duplicate error.
     */
    const email = this.form.get('email');
    // Clone the existing errors
    const existingErrors = { ...email.errors };
    // Ensure that duplicate error is removed (we're in the change handler for the duplicate error)
    delete existingErrors.duplicate;
    if (duplicateError) {
        // We have a new duplicate error, so add it.
        email.setErrors({ ...existingErrors, duplicate: duplicateError.errorMessage });
    } else if (Object.keys(existingErrors).length === 0) {
        // We have NO errors, so pass null
        email.setErrors(null);
    } else {
        // We have existing errors, but no new duplicate error. Pass the existing errors.
        email.setErrors(existingErrors);
    }
    this.changeDetector.markForCheck();
})