Home > Net >  Why FormRecord doesn't allow to use object as a first argument?
Why FormRecord doesn't allow to use object as a first argument?

Time:06-09

Angular 14 added a new class called FormRecord which allows to create form controls more dynamic than FormGroup. Docs got an example which goes like this

FormRecord accepts one generic argument, which describes the type of the controls it contains.

let numbers = new FormRecord({bill: '415-123-456'});
numbers.addControl('bob', '415-234-567');
numbers.removeControl('bill');

But when I use that example in my code I got an error

let numbers = new FormRecord({bill: '415-123-456'}); // TS2322: Type 'string' is not assignable to type 'AbstractControl<never, never>'. 
numbers.addControl('bob', '415-234-567'); // TS2345: Argument of type 'string' is not assignable to parameter of type 'AbstractControl '.

When it comes to package.json it looks like this

  "dependencies": {
    "@angular/animations": "^14.0.0",
    "@angular/common": "^14.0.0",
    "@angular/compiler": "^14.0.0",
    "@angular/core": "^14.0.0",
    "@angular/forms": "^14.0.0",
    (...)
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "^14.0.0",
    "@angular/cli": "~14.0.0",
    "@angular/compiler-cli": "^14.0.0",
    (...)
    "typescript": "~4.7.2"
  }

CodePudding user response:

I think that's a documentation error that didn't get caught during the release.

See the top of the documentation:

extends FormGroup<{[key: string]: TControl; }>

and this blog post:

languages: new FormRecord({
  english: new FormControl(true, { nonNullable: true }),
  french: new FormControl(false, { nonNullable: true })
});

The values of the object you pass to new FormRecord should be FormControl objects, not strings.

  • Related