2016-07-23 68 views
0

我是新手與角2 我有一個問題,但沒有嘗試過呢。 我想在這個列表創建待辦事項列表 但項目的名單有不同的組件&類(但是從同一母公司的每個組件繼承)角2是否有可能列出具有繼承項目

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

由於'AbstractTodoComponent'是一個普通班,你可以繼承它作爲一個普通班。關於條件渲染(看起來你在問什麼),似乎更好的方法是使用'* ngIf'或'[ngSwitch]'。 – acdcjunior

+0

你有比'* ngIf'或'ngSwitch'更好的方法嗎?我看到動態內容加載器,但它取代內容而不是組件 –

+0

實際上,您可以使用DynamicComponentLoader作爲替代方案。我用一個例子添加了一個答案。 – acdcjunior

回答

0

你可以利用DynamicComponentLoader根據每個todo的類型動態創建組件。

檢查demo plunker here

重要的代碼:

@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; 
    } 
    } 

} 
+0

但我如何過濾待辦事項,如果我有搜索框? 因爲這個技術不使用ngFor –

相關問題