1

I have the following problem with Angular 6:

I'm trying to manually set the errors property on a formControl with .setErrors() and setting the value with .setValue() afterwards. The setValue method. To my detriment, .setValue() re-runs the validation and resets the errors property on the formControl to null. Like so:

import { OnInit} from '@angular/core';
import { FormControl} from '@angular/forms';

export class CustomComponent implements OnInit {
  formControl: FormControl;

  ngOnInit() {
    this.formControl = new FormControl();
    this.formControl.setErrors({required: true});
    this.formControl.setValue('foo'); // resets formControl.errors to null
    console.log(this.formControl.errors); // returns null
  }

}

Any ideas?

1 Answer 1

2

I actually figured it out. You can use .disable() to disable the automatic validation on the formControl - works great if you're using the formControl in an abstract way, as in my case.

import { OnInit} from '@angular/core';
import { FormControl} from '@angular/forms';

export class CustomComponent implements OnInit {
  formControl: FormControl;

  ngOnInit() {
    this.formControl = new FormControl();
    this.formControl.disable({onlySelf: true, emitEvent: false});
    this.formControl.setErrors({required: true});
    this.formControl.setValue('foo');
    console.log(this.formControl.errors); // returns 'foo'
  }

}

You can enable the formControl again with .enable(), if you need to interact with it in the template. See more here https://angular.io/api/forms/AbstractControl#disable

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.