具有多个子组件实例的Angular2父组件

时间:2016-11-22 19:14:22

标签: angular angular2-template

我有一个父组件,其模板引用同一子组件的多个实例。子组件将具有相同的组件/模板实现,但应多次实例化并呈现不同的数据集。我查看了许多帖子,例如Instance Angular 2 Component Two times,但所有帖子似乎都使用了不推荐的指令组件属性。

parent.template.html

<child-component data="foo"></child-component>
<child-component data="baz"></child-component>

data.service.ts

import { Injectable } from '@angular/core';

@Injectable()
export class DataService {
    getFooData(): Object {
        return { name: 'Foo' }
    }

    getBazData(): Object {
        return { name: 'Baz' }
    }
 }

child.template.html

<h1>{{objectToRender.name}}</h1>

child.component.ts

import { Component, Input, OnInit } from '@angular/core';
import { DataService }              from './data.service';

@Component({
    selector:       'child-component',
    templateUrl:    'child.template.html',
    providers:      [ DataService ]
})
export class ChildComponent  implements OnInit {
    @Input() data: String;
    objectToRender: Object;
    ds:             DataService

    constructor( private dataService: DataService ) {
        this.ds = dataService;
    }

    ngOnInit(){
        switch( this.data ) {
            case 'foo':
                this.objectToRender = this.ds.getFooData();
            case 'baz':
                this.objectToRender = this.ds.getBazData();
        }
    }

}    

app.module.ts

import { NgModule }             from '@angular/core';
import { BrowserModule }        from '@angular/platform-browser';
import { AppComponent }         from './app.component';
import { ParentComponent}     from './parent.component';
import { ChildComponent }     from './child.component';


@NgModule({
    imports:      [ BrowserModule ],
    declarations: [ AppComponent, ParentComponent, ChildComponent ],
    bootstrap:    [ AppComponent ]
})
export class AppModule { }

结果: 巴兹 巴兹

预期: 富 巴兹

在这个Plunker中可以看到我的问题的简化版本。我已经将所有模板文件一起省略,并将根应用程序组件用作父项。 https://plnkr.co/edit/QI5lGH3S9a5o3b1ajPBl?p=preview

非常感谢提前!

1 个答案:

答案 0 :(得分:3)

缺少break;

    switch( this.data ) {
        case 'foo':
            this.objectToRender = this.ds.getFooData();
            break;
        case 'baz':
            this.objectToRender = this.ds.getBazData();
            break;
    }

Plunker example