尽管我没有编译器错误,并且智能感知正在完成不同的组件,但数据并没有在视图中设置。如何在Angular 2中设置组件的属性值?
app.component.ts
onSelect(item: TodoItem) {
this.SelectItemComponent.selectedItem = { Name: 'name', Key: 'key' };
}
选择-item.component.ts
ngOnInit() {
this.selectedItem = { Name: 'Name', Key: 'Key' };
}
在select-item.component.ts
的ngOnInit()
正确地设置视图的值,而是从selectedItem
组app.component.ts
不会更新视图。
全码: app.component.ts
import { Inject, Component } from 'angular2/core';
import { DataService } from './data.service';
import { TodoItem } from './TodoItem';
import { AddItemComponent } from './add-item.component';
import { SelectItemComponent } from './select-item.component';
@Component({
selector: 'app',
directives: [
AddItemComponent,
SelectItemComponent
],
templateUrl: 'templates/app.html'
})
export class AppComponent {
private items: Array<TodoItem> = new Array<TodoItem>();
private selectedItem: TodoItem;
public SelectItemComponent: SelectItemComponent;
constructor(@Inject(DataService) public dataService: DataService) {
}
ngOnInit() {
this.dataService.collection$.subscribe(latestCollection => {
this.items = latestCollection;
});
this.dataService.getItems();
}
onSelect(item: TodoItem) {
this.SelectItemComponent.selectedItem = { Name: item.Name, Key: item.Key };
}
}
选择-item.component.ts
import { Component, Inject } from 'angular2/core';
import { TodoItem } from './TodoItem';
import { DataService } from './data.service';
import { Observable } from 'rxjs/Observable';
@Component({
selector: 'select-item',
templateUrl: 'templates/select-item.html'
})
export class SelectItemComponent {
public selectedItem: TodoItem;
public collection$: Observable<Array<TodoItem>>;
private _collectionObserver: any;
private _collection: Array<TodoItem>;
constructor(@Inject(DataService) public dataService: DataService) { }
ngOnInit() {
this.selectedItem = { Name: 'Name', Key: 'Key' };
}
}
看看这个答案,它的一个办法做到这一点 - > http://stackoverflow.com/questions/35093864/更新数据在一个组件上基于点击的另一个组件-i/35094087#35094087 –
这两个组件是如何相关的?他们中的一个是另一个的孩子吗?另外,AppComponent.SelectItemComponent'初始化在哪里? –