TILT-Typed Reactive Forms and arrays–part 26

I want now to pass to typed reactive forms ( with Angular 14 )- what is good is that are typed , i.e. I can see errors if some property is not correct.

The code previously was

profileForm = this.fb.group({
    url: [''],
    publicTILTS: this.fb.array([])
  });

Now the code looks like

profileForm =  new FormGroup({
    url: new FormControl(''),
    publicTILTS: new FormArray([new FormControl(new TILT())])
  });

And you may ask – what is the difference ? The difference is type inferring from generics. For example , the constructor for FormControl ( after several steps, since it is a interface)

new <T = any>(value: FormControlState<T> | T  //more code

So the above definition is , actually, this one:

profileForm =  new FormGroup({
    url: new FormControl<string>(''),
    publicTILTS: new FormArray<FormControl<TILT|null>>([new FormControl<TILT>(new TILT())])
  });

Now the other modifications are

  1. Get rid of formArray

  2. typed data in HTML :
    <div  *ngFor="let item of profileForm.value.publicTILTS; let i = index;let f=first"> 
  3. modify the string url It was hardcoded:
  tap(it => this.profileForm.controls['url'].setValue(it)),

Now it is typed patchValue that has a Partial – typed!

tap(it => this.profileForm.patchValue({url:it}))

Just technical, the relevant definitions are

patchValue(value: ɵFormGroupValue<TControl>, options?: {
        onlySelf?: boolean;
        emitEvent?: boolean;
    }): void;

export declare type ɵFormGroupValue<T extends {
    [K in keyof T]?: AbstractControl<any>;
}> = ɵTypedOrUntyped<T, Partial<{
    [K in keyof T]: ɵValue<T[K]>;
}>, {
    [key: string]: any;
}>;
  1. Modified the array – patchValue does not work with arrays, so setControl to the rescue

Now it is

//this do not work - do not modify the array length, but the contents
// this.profileForm.patchValue({publicTILTS: [...it]});
//setControl<K extends string & keyof TControl>
this.profileForm.setControl("publicTILTS",new FormArray(it.map(a=>new FormControl(a))));        

Again it is typed , even if it seems a string- I have put a comment above with the definition – see keyof ? It will raise an error at compile time!

For the end user, the site is THE SAME. However, the code now is typed – and , yes, this is a great deal for programmer!