在我的 Angular 应用程序中:
当组件使用在其直接父(抽象)类中定义的输入时,一切正常。
当组件使用在 2 级向上父(抽象)类中定义的输入时,
ng build
或 ng serve
会给出错误。例如,我有4节课:
export abstract class AbstractAComponent {
@Input() myInput: string;
}
export abstract class AbstractBComponent extends AbstractAComponent {}
@Component({
selector: 'app-one',
templateUrl: './one.component.html',
styleUrls: ['./one.component.scss']
})
export class OneComponent extends AbstractAComponent {}
@Component({
selector: 'app-two',
templateUrl: './two.component.html',
styleUrls: ['./two.component.scss']
})
export class TwoComponent extends AbstractBComponent {}
这就是我使用它们的方式:
<app-one [myInput]="'value 1'"></app-one>
<app-two [myInput]="'value 2'"></app-two>
简而言之: -
@Input() myInput
定义于 AbstractAComponent
- OneComponent
直接延伸AbstractAComponent
- TwoComponent
延伸 AbstractBComponent
延伸 AbstractAComponent
预期行为: -
OneComponent
和 TwoComponent
都应该有 @Input() myInput
当前行为: - 看起来
TwoComponent
没有正确继承 @Input() myInput
我收到以下错误:
ERROR in src/app/app.component.html:2:10 - error NG8002: Can't bind to 'myInput' since it isn't a known property of 'app-two'.
1. If 'app-two' is an Angular component and it has 'myInput' input, then verify that it is part of this module.
2. If 'app-two' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.
3. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component.
我最初认为这是一个错误,并在here报告了它,elvisbegovic
实际上向我指出了解决方案解决方案是将
@Directive()
添加到您的抽象类中,例如我的:
import { Directive, Input } from '@angular/core';
@Directive()
export abstract class AbstractAComponent {
@Input() myInput: string;
}
import { Directive } from '@angular/core';
@Directive()
export abstract class AbstractBComponent extends AbstractAComponent {}
让我们试试这个: 在
AbstractAComponent
中,添加了@Directive()
。
@Directive()
export abstract class AbstractAComponent {
@Input() myInput: string;
}
并且在 OneComponent 中,在构造函数中添加了
super();
。这对我有用。
export class OneComponent extends AbstractAComponent {
constructor() {
super();
}
}
对于 Angular 17.x 和输入信号来说是类似的。只需在抽象类中使用组件装饰器即可。
抽象类:
@Component({template: ``,})
export abstract class AbstractEntitiesListComponent<T> {
data = input.required<T[]>();
messages = input<MessageInterface[]>([]);
isLoading = input<boolean>(false);
noData = input<boolean>(false);
header = input<string | undefined>(undefined);
readonly columns!: Array<[keyof T, string]>;
protected abstract getColumns(): Array<[keyof T, string]>;
constructor() {
this.columns = this.getColumns();
}
}
继承类:
@Component({
...
template: `
<common-basic-table [columns]="columns" [data]="data()"></common-basic-table>
`,
...
})
export class ProductsComponent extends AbstractEntitiesListComponent<ProductInterface>{
protected getColumns(): Array<[keyof ProductInterface, string]> {
return [
['name', 'Name'],
['category', 'Category'],
['description', 'Description'],
['inventoryStatus', 'Status'],
['code', 'Code'],
['price', 'Price'],
['quantity', 'Quantity'],
['rating', 'Rating'],
];
}
}