gpt4 book ai didi

typescript - angular2中组件之间的多态性

转载 作者:太空狗 更新时间:2023-10-29 17:15:41 27 4
gpt4 key购买 nike

我有不同的类(class)(模特),他们是 parent 的 child 。每个 child 都有自己的形式,但我希望具有父引用的组件根据 child 呈现特定形式。一个例子:

模型

export interface Item {
title: string;
}

export class Exercise implements Item {
constructor(public title:string, public description:string);
}

export class Break implements Item {
constructor(public title:string, public time:number);
}

表格

@Component({
selector: 'item-form',
template: `<item></item>
`,
inputs: ['model:item']
})
export abstract class ItemFormComponent {
model: Item;
}

@Component({
selector: 'item-form',
template: `
<form #exerciseForm="ngForm">
<input type="text" class="form-control" required
[(ngModel)]="model.title"
ngControl="title" #name="ngForm" >
<input type="text" class="form-control" required
[(ngModel)]="model.description"
ngControl="desription" #name="ngForm" >
</form>
`,
providers: [ExerciseService],
inputs: ['model:exercise']
})
export class ExerciseFormComponent extends ItemFormComponent {
model = new Exercise("Title", "Description");

constructor(private _exerciseService: ExerciseService) {
super();
}
}

@Component({
selector: 'item-form',
template: `
<form #exerciseForm="ngForm">
<input type="text" class="form-control" required
[(ngModel)]="model.title"
ngControl="title" #name="ngForm" >
<input type="text" class="form-control" required
[(ngModel)]="model.time"
ngControl="number" #name="ngForm" >
</form>
`,
inputs: ['model:break']
})
export class BreakFormComponent extends ItemFormComponent {
model = new Break("Title", 10);

}

应用

@Component({
selector: 'app',
template: `
<h1>App</h1>
<div *ngFor="#item of items">
<item-form [model]="item"></item-form> <!-- HERE IS WHERE FORM SHOULD BE INSERTED! -->
</div>
`,
directives: [ItemFormComponent]
})
export class App {
items: Item[] = [new Exercise("Exercise", "Description"), new Break("Break", 10)];
}

最佳答案

我想你需要这样的东西:

      <div *ngFor="#item of items">
<item-form-a *ngIf="item instanceOf A" [model]="item"></item-form-a>
<item-form-b *ngIf="item instanceOf B" [model]="item"></item-form-a>
</div>

我不使用 TypeScript,也不知道 Angular 表达式是否支持 instanceOf。如果不是,您需要将检查移动到 App 的函数并调用它,如 *ngIf="isInstanceOf(item, A)

关于typescript - angular2中组件之间的多态性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35612284/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com