Reputation: 355
I'm trying to make an abstract component in angular but am getting following error:
Error: src/app/app.module.ts:191:5 - error TS2322: Type 'typeof AbstractFormComponent' is not assignable to type 'any[] | Type<any>'.
Type 'typeof AbstractFormComponent' is not assignable to type 'Type<any>'.
Cannot assign an abstract constructor type to a non-abstract constructor type.
191 AbstractFormComponent
~~~~~~~~~~~~~~~~~~~~~
This is my abstract Component:
@Component({
selector: 'app-abstract-form',
templateUrl: './abstract-form.component.html',
styleUrls: ['./abstract-form.component.scss']
})
export abstract class AbstractFormComponent implements OnInit, AfterViewInit {
protected constructor(protected formService: FormService) {
}
protected abstract getForms(): AbstractControl[];
ngOnInit(): void {
}
ngAfterViewInit(): void {
this.getForms().forEach(f => this.formService.addForm(f));
}
}
It seems like Angular has problems with the constructor but I need the constructor for the service so I cannot delete it. Is there any way that I can use abstract classes with a constructor/injecting services?
Upvotes: 9
Views: 8806
Reputation: 249
An abstract component class like an interface, is just a boilerplate, and can not be instanced. So you can not include it in the module declaration array. Just use it as an interface.
import {SearchDataGridBaseComponent} from "@shared"; // no need decalre in the module
export class HddataComponent extends SearchDataGridBaseComponent{
.......
}
Upvotes: 0
Reputation: 380
Using an abstract class for a component seems to work okay in Angular 14. The error noted above (Type 'typeof myAbstractClass' is not assignable to type 'Type') can be remedied by just not trying to include the abstract class in a module and import it in the child classes from that module. Just have the descendants import the class directly from the abstractclass.ts file. I am using DI on the abstract constructor. I only use a constructor in the child class if I need to inject something not used in the abstract class. Works great.
Upvotes: 0
Reputation: 3193
This looks like a known typescript issue. https://github.com/microsoft/tsyringe/issues/20 .
You can use @ts-ignore to skip build time type checking.
Upvotes: 0
Reputation: 355
Solution is just not adding the abstract component to app.modules. I can still use it as abstract Component and I don't get any errors.
Upvotes: 14