0

Angular 14 has released the Typed Forms concept. I am trying to use that in place of a FormGroup. ALl okay in the ts, but in HTML, how shall we bind it to the HTML tag, like we used to do for FormGroup?

For formgroup we did <form [formGroup]="myForm"> It seems there no such option for FormRecord. Please can someone help me here?

Rahul Mukherjee
  • 107
  • 1
  • 1
  • 10

1 Answers1

0

Property binding techniques like <form [formGroup]="myForm"> should still work with FormRecord because FormRecord extends FormGroup.


From the documentation on FormRecord, it can be seen that it extends FormGroup.

class FormRecord<TControl extends AbstractControl<ɵValue<TControl>, ɵRawValue<TControl>> = AbstractControl, TControl> extends FormGroup<{
    [key: string]: TControl;
}> 

In general, any technique that's applicable to FormGroup will work with FormRecord as well, like getting a single value:

this.formGroup.get('name of you control').value

Here's a simple somewhat dynamic StackBlitz example: https://stackblitz.com/edit/angular-v14-playground-c1ak5m?embed=1&file=src/main.ts

export class AppComponent implements OnInit {

  public myForm: FormRecord;
  public formKeys = ['Andrew', 'Barry']

  ngOnInit(): void {
    this.myForm = new FormRecord<FormControl<string|null>>({});
    this.formKeys.forEach((key, i) => 
      this.myForm.addControl(key, new FormControl(`${(i + 1) * 100} Default-Value St.`))
    );

  }
    <div>
      <form [formGroup]="myForm">
        <div *ngFor="let key of formKeys">
          <b>{{key}}: </b><input  [formControlName]="key"><br/>
        </div>
      </form>
    </div>
    <div>
    <br/>
    <div *ngFor="let key of formKeys">
      <div>{{key}}: {{myForm.get(key).value}}</div>
    </div>
    </div>
OSH
  • 741
  • 4
  • 11