0

I have a child component with an input tag

<input [formControl]="control">

component.ts file

@Input() control: FormControl;

And using it in the parent as

<app-input [control]="f['email']"></app-input>
                      ~~~~~~~~~~

component.ts file


public form: FormGroup;

constructor(
    private fb: FormBuilder,
  ) {
    this.form = this.fb.group({
      email: ['', [
        Validators.email,
        Validators.required
      ]],
    });
}

get f() {
    return this.form.controls;
}

But it is giving an error in the HTML control assignment.

Type AbstractControl<any> is not assignable to type FormControl 
Anuj TBE
  • 9,198
  • 27
  • 136
  • 285

2 Answers2

0
get f() {
  return this.form.controls as {[key: string]: FormControl } ;
} 

Because form groups and arrays can contain groups, arrays or controls, they return abstract controls. You have to explicitly state they are controls.

MGX
  • 2,534
  • 2
  • 14
0

What you can do is the following:

public form: FormGroup = this.fb.group({
  email: ['', [
    Validators.email,
    Validators.required
  ]],
});

constructor(private fb: FormBuilder) 
{}`

Then in the parent html: <app-input [control]="form.controls.email"></app-input>

This way the form control values are available during development as types

Leroy Meijer
  • 1,169
  • 17
  • 40
  • It still has the same error. – Anuj TBE Jun 29 '23 at 10:32
  • I have it working like this. You maybe tried this? https://github.com/ngx-formly/ngx-formly/issues/2842#issuecomment-931865585 Also is your ngModule set with the correct modules like: FormsModule and ReactiveFormsModule Also check this one: https://github.com/primefaces/primeng/issues/9636 This is my tsconfig.json for the angular part }, "angularCompilerOptions": { "enableI18nLegacyMessageIdFormat": false, "strictInjectionParameters": true, "strictPropertyInitialization":false, "strictInputAccessModifiers": true, "strictTemplates": true } – Leroy Meijer Jun 29 '23 at 11:28
  • @LeroyMeijer, it's problem with "strict mode". The clasic solution is use a getter, in Angular 16 you can use transform (see this [SO](https://stackoverflow.com/questions/76570807/typescript-error-when-trying-to-implement-nested-reactive-forms-in-angular/76571571#76571571) -is related to a formGroup but you can use the same with a FormControl. BTW Threr'e another aproach that it's use viewProvider, like this [another SO](https://stackoverflow.com/questions/73455294/how-do-i-get-access-to-from-control-from-another-component-in-angular/73457780#73457780) – Eliseo Jun 29 '23 at 11:33
  • Good find @Eliseo, I'm using Angular 16.1.3 with the strict settings like my comment above and it's working. Thanks for this improvement – Leroy Meijer Jun 29 '23 at 11:36