Esteban Chornet
Esteban Chornet

Reputation: 1227

Angular using disable form control typed forms

I'm updating all my angular forms to typed forms. I define it like follows:

readonly personForm: FormGroup<{
    name: FormControl<string>
    favorites: FormControl<string[] | null>
}>;

And I initialize it like:

this.personForm = this.fb.group({
    name: this.fb.nonNullable.control("", Validators.required),
    favorites: new FormControl({ value: [""], disabled: false})
});

Somewhere in the code I'm resetting the form once I get the data from the API. The "favorites" is a select from a list from another API method, let's call it food. If this food list is empty, then

this.personForm.reset({
    name: person.name,
    favorites: {
        value: person.favorites || [],
        disabled: this.food && this.food.length < 1
    }
});

Where person is the constant which contains my API data response.

On this favorites assignation I get a TS error: enter image description here

So I'm guessing the way I'm defining the FormControl it's not correct at all. How do I have to define it?

Upvotes: 0

Views: 3396

Answers (2)

MGX
MGX

Reputation: 3521

As a side note :

  • If you use the form builder, you only need it on group
  • If you have a required validator, you don't need the nonNullable option

Your code can then become :

this.personForm = this.fb.group({
    name: ['', [Validators.required]],
    favorites: ''
});

Then, if you implement the solution, you can make it more concise too :

this.personForm.patchValue({
    name: person.name,
    favorites: person.favorites ?? []
});
if (!this.food?.length) this.personForm.get('favorites').disable();

Upvotes: 2

Anton Marinenko
Anton Marinenko

Reputation: 2982

You have to patch your control value with it's type:

  favorites: person.favorites || []

And then check if it should be disabled:

const favoritesControl = this.personForm.controls.favorites;

if (this.food && this.food.length < 1 && favoritesControl.enabled) {
  favoritesControl.disable();
}

P.s. your code works with UntypedFormControl because of wrong value assigned. In your reset function:

favorites: {
        value: person.favorites || [],
        disabled: this.food && this.food.length < 1
    }

assigns object value with props. And actually it will not be disabled even if the same prop disabled is true. And now your control have not a string array value, but object.

Upvotes: 0

Related Questions