我是角度2的新手 我有一个问题,但还没有尝试过。 我想创建一个Todo列表列表 但此列表中的项目具有不同的组件和&类(但每个Component继承自同一个Parent)
class Todo {}
class TodoPic extends Todo {}
class TodoVideo extends Todo {}
@Component({
selector: 'todo',
template: '...'
})
class AbstractTodoComponent {
todo: Todo;
}
@Component({
selector: 'todo-pic',
template: '...'
})
class TodoPicComponent extends AbstractTodoComponent {}
@Component({
selector: 'todo-video',
template: '...'
})
class TodoVideoComponent extends AbstractTodoComponent {}
并像这样使用
@Component({
selector: 'app',
template: '<todo *ngFor="let item in todoList"></todo>'
})
class AppComponent {
todoList: Todo[]
constructor() {
todoList.push(new TodoPic())
todoList.push(new TodoVideo())
}
}
答案 0 :(得分:0)
您可以根据每个todo
的类型,利用DynamicComponentLoader
动态创建组件。
重要代码:
@Component({
selector: 'app',
template: 'stuff before<hr><div #todoLocation></div><hr>stuff after'
})
class AppComponent {
todoList: Todo[] = [new TodoPic(), new TodoVideo()];
@ViewChild('todoLocation', {read: ViewContainerRef}) todoLocation:ViewContainerRef;
constructor(private dcl: DynamicComponentLoader) { }
ngAfterViewInit() {
this.todoList.forEach(todo => this.loadComponentForTodo(todo));
}
loadComponentForTodo(todo: Todo) {
let componentForType = this.inferComponentForType(todo);
// this is where the component is created and loaded
this.dcl.loadNextToLocation(componentForType, this.todoLocation)
.then((c:ComponentRef) => {
c.instance.todo = todo;
});
}
inferComponentForType(todo: Todo) {
let componentForType = AbstractTodoComponent;
if (todo instanceof TodoPic) {
return TodoPicComponent;
} if (todo instanceof TodoVideo) {
return TodoVideoComponent;
}
}
}