【发布时间】:2018-03-16 21:58:28
【问题描述】:
我有一个 Ionic 应用程序,我在其中创建了一个组件来显示对象的一些数据。我的问题是,当我更新托管组件的父级中的数据时,组件内的数据不会更新:
my-card.component.ts
@Component({
selector: 'my-card',
templateUrl: './my-card.html'
})
export class MyCard {
@Input('item') public item: any;
@Output() itemChange = new EventEmitter();
constructor() {
}
ngOnInit() {
// I do an ajax call here and populate more fields in the item.
this.getMoreData().subscribe(data => {
if (data.item){
this.item = data.item;
}
this.itemChange.emit(this.item);
});
}
}
我的卡片.html
<div class="comment-wrapper" *ngFor="let subitem of item.subitems">
{{subitem.title}}
</div>
在父级中我使用这样的组件:
<my-card [(item)]="item"></my-card>
还有父级的 ts 文件:
@IonicPage()
@Component({
selector: 'page-one',
templateUrl: 'one.html',
})
export class OnePage {
public item = null;
constructor(public navCtrl: NavController, public navParams: NavParams) {
this.item = {id:1, subitems:[]};
}
addSubItem():void{
// AJAX call to save the new item to DB and return the new subitem.
this.addNewSubItem().subscribe(data => {
let newSubItem = data.item;
this.item.subitems.push(newSubItem);
}
}
}
所以当我调用 addSubItem() 函数时,它不会更新组件并且 ngFor 循环仍然不显示任何内容。
【问题讨论】:
-
这对我来说毫无意义,你正在传递输入,但没有在子组件中使用它。
-
您好,抱歉,如果我的代码不是很清楚,我不得不剥离一些代码。我基本上传入了一个仅包含 Id 的项目对象,然后在加载卡片组件时,我执行了一个 ajax 调用来补充其余的项目字段。
-
好的,我现在明白了。因此,您谈论双向绑定,因此父项需要与子项具有相同的值(在 api 请求之后),或者您在父项中所做的事情足以反映在子项中。我正在考虑解决方案,所以这很重要:)
-
好的,这样父级会将 id 传递给子级,而子级会将 AJAX 的结果混合起来。然后用户将与创建新子项的父元素进行交互,然后我需要在 clild 视图中显示该新子项。这有意义吗?
标签: javascript angular typescript ionic3 angular2-components