我有不同的班级(模特),他们是父母的孩子.每个孩子都有自己的形式,但我希望具有父参考的组件根据孩子呈现特定的形式.一个例子:
原文链接:https://www.f2er.com/angularjs/142004.html楷模
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)]; }