如何解决在继承抽象类的类的实例上调用方法
我在这里有这个抽象类:
export abstract class BaseStepComponent {
/** base-step ctor */
constructor() {
}
abstract getValue(): string;
}
和一个继承它的组件:
export class SingleChoiceStepComponent extends BaseStepComponent {
/** single-choice-step ctor */
constructor() {
super();
}
@ViewChild("itemList") itemList: ElementRef;
getValue(): string {
return this.itemList.nativeElement.value;
}
}
我有一些这样的组件,它们在getValue()
中有不同的逻辑
在我的应用程序中的其他地方,我在一个组件中拥有该成员:
stepItems: QueryList<any>;
@ViewChildren("stepItem") set stepItemsContent(content: QueryList<any>) {
let items = content.toArray();
if (items.length > 0) {
this.stepItems = content;
}
}
“步骤”是向导(多页表单)中的字段,应用程序并不真正知道呈现的“步骤”的类型以及它们的数量(可通过管理UI进行配置),但是它们都是继承BaseStepComponent
稍后,我想收集getValue()
返回的值,但是我有下面的注释中提到的问题。
let values: any[] = [];
this.stepItems.forEach(step => {
let v = step.getValue(); //works in IDE,not at runtime,sadly.
values.push({ key: step.key,value: v });
});
由于BaseStepComponent
是抽象的,因此我无法执行以下操作:
let instance = new BaseStepComponent();
instance = Object.assign(instance,step);
所以我有点卡住了。知道如何实现吗?
解决方法
您可以使用类似以下的内容,
export abstract class BaseStepComponent {
/** base-step ctor */
constructor() {}
abstract getValue(): string;
}
@Component({
selector: "step1",template: `
<h1>Step 1</h1>
`,providers: [{ provide: BaseStepComponent,useExisting: Step1Component }]
})
export class Step1Component extends BaseStepComponent {
@Input() name: string;
getValue(): string {
return "Step1Component";
}
}
@Component({
selector: "step2",template: `
<h1>Step 2</h1>
`,useExisting: Step2Component }]
})
export class Step2Component extends BaseStepComponent {
@Input() name: string;
getValue(): string {
return "Step2Component";
}
}
要使用它,
export class AppComponent {
name = "Angular " + VERSION.major;
@ViewChildren(BaseStepComponent) items: QueryList<BaseStepComponent>;
ngAfterViewInit() {
this.items.map((step: BaseStepComponent) => {
console.log(step.getValue());
});
}
}
这是stackblitz。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。