【发布时间】:2017-04-06 14:27:01
【问题描述】:
我有一个带有模板的父组件,该模板引用同一个子组件的多个实例。子组件将具有相同的组件/模板实现,但应多次实例化并呈现不同的数据集。我查看了很多类似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
提前非常感谢!
【问题讨论】:
-
什么是“不推荐使用的指令组件属性”?
-
你不应该去 *ngFor 吗?
-
我不明白问题出在哪里。你想达到什么目的?当前的行为是什么?预期的行为是什么?
-
@GünterZöchbauer,在 Angular 2 的最终版本中,
@Component装饰器上的directives属性已被弃用。 -
angular.io/docs/ts/latest/guide/ngmodule.html。只需将其移至
declarations: [...]或@NgModule()