sandrooco
sandrooco

Reputation: 8716

Angular Typed Forms: How to correctly type and create dynamic fields?

I have the following formgroup:

this.formBuilder.group<{
    id: number;
    nameDe?: FormControl<string>;
    nameFr?: FormControl<string>;
    nameIt?: FormControl<string>;
}>({
    id: value?.id || null
});

Focus is on the "nameXY" fields. These are added dynamically/based on conditions.

languages.forEach((lang) => { // languages can be ['De', 'Fr'] or ['Fr', 'It']
    const nameIdentifier = 'name' + lang;
    formGroup.addControl(nameIdentifier, new FormControl<string>(value?.[nameIdentifier] || '', Validators.required));
});

Now I get this error:

Argument of type 'string' is not assignable to parameter of type ...

Obviously it's because nameIdentifier is only a string and not 'nameDe' | 'nameFr'| 'nameIt'.

The first approach I tried was to explicitely define the type for nameIdentifier:

const nameIdentifier: 'nameDe' | 'nameFr' | 'nameIt' = 'name' + lang;

Then I get this error:

Type 'string' is not assignable to type '"nameDe" | "nameFr" | "nameIt"'.ts(2322)

Now I'm out of ideas. :) Are there any clean approaches without having to use tons of explicit typing?

Upvotes: 0

Views: 963

Answers (1)

Chellappan வ
Chellappan வ

Reputation: 27303

Try type assertion using as keyword.

const nameIdentifier = ('name' + lang) as 'nameDe' | 'nameFr' | 'nameIt';

Or

you can use FormRecord

Upvotes: 1

Related Questions