我有不同的班级(模特),他们是父母的孩子。每个孩子都有自己的形式,但我希望具有父参考的组件根据孩子呈现特定的形式。一个例子:
模型
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)];
}
答案 0 :(得分:1)
我认为你需要这样的东西:
<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)
。