Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Template error Type 'AbstractControl' is not assignable to type 'FormControl'

Why am I getting this error?

The following code works in another application

          <input class="form-control form-control-sm" type="number" min="0"
            [formControl]='invoiceForm.get("quantity")'>

in this new application it works too but still complaining in the terminal

  Type 'AbstractControl' is not assignable to type 'FormControl'.
like image 797
Bellash Avatar asked Jun 04 '21 09:06

Bellash


Video Answer


3 Answers

<input type="password" placeholder="Confirm Password" class="form-control" [formControl]="$any(myForm).controls['confirmpassword']"/> 

Use the $any function to disable type checking. I resolved my error by using this.

like image 158
Bhagyashri Chouhan Avatar answered Oct 09 '22 17:10

Bhagyashri Chouhan


This issue might come from tsconfig.json if you're using Angular 9 or above

"angularCompilerOptions": {
    ...
    "strictTemplates": true <-- causing "Type 'AbstractControl' is not assignable to type 'FormControl'"
  }

First Option

by setting "strictTemplates": false might temporary "solve" the problem

Second Option

by convert the AbstractControl to FormControl through template, so your .ts file should have

convertToFormControl(absCtrl: AbstractControl | null): FormControl {
    const ctrl = absCtrl as FormControl;
    return ctrl;
  }

and your html

<input
    type="text"
    [formControl]="convertToFormControl(invoiceForm.get("quantity"))"
  />
like image 27
jdczw Avatar answered Oct 09 '22 17:10

jdczw


If someone else still have this issue, I share my solution, which is almost the same as Bellash was described but with better perfomance. For this example:

<input class="form-control form-control-sm" type="number" min="0"
        [formControl]='invoiceForm.get("quantity")' | formControl>

we just need to create and use pipe which will return for us value with correct type

@Pipe({
    name: 'formControl',
})
export class FormControlPipe implements PipeTransform {
    transform(value: AbstractControl): FormControl<typeof value['value']> {
        return value as FormControl<typeof value['value']>;
    }
}

In this way you will have better perfomance since pipe transform function will be called only when provided form will be changed.

Generally it is bad practice to use functions in templates, because this functions will be called on each lifecycle change, and will have big perfomance issues on bigger projects. The best way is to use pipes, which generally was developed exactly for such purposes, to transform some values on rendering only when this will be changed. Hope this will help someone)

like image 10
Avetik Avatar answered Oct 09 '22 19:10

Avetik