儘管我沒有編譯器錯誤,並且智能感知正在完成不同的組件,但數據並沒有在視圖中設置。如何在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'初始化在哪裏? –