2016-07-23 9 views
0

私は角2の初心者です 私は質問がありますが、まだ試していません。私はこのリストにTODOリスト なく、アイテムのリストを作成したい は異なるコンポーネント&クラス(同じ親からのすべてのコンポーネントの継承)角度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'よりも優れたアプローチがありますか? Dynamic Content Loaderが表示されますが、コンポーネントではなくコンテンツが置き換えられます –

+0

実際には、代わりに「DynamicComponentLoader」を使用できます。私は例を使って答えを加えました。 – acdcjunior

答えて

0

あなたはできるように使用します各todoのタイプに従って、DynamicComponentLoaderを利用してコンポーネントを動的に作成します。

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

検索ボックスがある場合、どのようにtodoアイテムをフィルタリングできますか?この技術ではngForを使用しないため、 –

関連する問題