angular - 是否需要双向绑定才能在需要的组件之间共享数据?
问题描述
当从父组件添加新数据时,我在弄清楚如何在子组件中更新数据时遇到了一些麻烦。
我有一个看起来像这样的模板:
<ion-content>
<app-feed-comments [comments]="comments" [userId]="userId" (newCommentsEvent)="newComments($event)"></app-feed-comments>
</ion-content>
<ion-footer>
<ion-toolbar>
<ion-item lines="none">
<ion-textarea #commentarea [(ngModel)]="comment" (ionInput)="textinput($event)" placeholder="Write a comment..." rows="1"></ion-textarea>
</ion-item>
<ion-buttons slot="end">
<ion-button color="medium" (click)="addComment()" [disabled]="comment.length < 5">
<ion-icon slot="icon-only" name="send"></ion-icon>
</ion-button>
</ion-buttons>
</ion-toolbar>
</ion-footer>
我将 my 传递comments
给子组件,但是当我从该addComment
方法添加新评论时,它不会将新评论推送到子组件。
我正在使用EventEmitter
一个无限滚动容量向父组件输出新评论。
这是我addComment
在我的feed.ts
文件中的方法:
addComment() {
let commentData = {
feedID: this.feedId,
comment: this.comment
};
this.api.post('feed/comment', commentData).subscribe((response:any) => {
if (!response.status.error) {
this.newComments(response.data.comment);
this.comment = '';
setTimeout(() => {
this.content.scrollToBottom();
});
}
});
}
newComments(comments:any) {
this.comments.push(...comments);
}
关于实现这一目标的最佳方法的任何想法?我是不是走错了路,还是我忽略了一些事情?
解决方案
您不需要(必然)EventEmitter
在父组件中需要 an ,而是子组件必须监听其输入的变化。
这可以通过在子组件中实现OnChanges
接口和方法来实现。ngOnChanges
如果子组件“直接”使用@Input
变量,则有时不需要这样做,但是如果您需要在输入更改时执行某些操作,ngOnChanges
则可以实现该方法。
推荐阅读
- c# - 处理选择点击事件datagridview
- python - 重命名文件夹后,QFileSystemModel 和 QTreeView 返回错误的路径
- java - 在 wicket 中调用 javascript 并将 Wicket 中的值设置为参数
- plugins - 求硕士项目插件架构框架的建议
- css - 如何摆脱在移动视图中单击的元素周围单击时出现的蓝色框?
- python - 使用 python 进行边际似然优化
- python - 将列表中的数据拆分到自己的列
- google-cloud-platform - Cloud Data Fusion 定价 - 开发与执行
- php - PHP用回声修复未定义的错误?但不起作用
- javascript - 使用 Javascript/jQuery 从 CDATA 渲染 HTML