首页 > 解决方案 > 是否需要双向绑定才能在需要的组件之间共享数据?

问题描述

当从父组件添加新数据时,我在弄清楚如何在子组件中更新数据时遇到了一些麻烦。

我有一个看起来像这样的模板:

<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);
  }

关于实现这一目标的最佳方法的任何想法?我是不是走错了路,还是我忽略了一些事情?

标签: angular

解决方案


您不需要(必然)EventEmitter在父组件中需要 an ,而是子组件必须监听其输入的变化。

这可以通过在子组件中实现OnChanges接口和方法来实现。ngOnChanges

如果子组件“直接”使用@Input变量,则有时不需要这样做,但是如果您需要在输入更改时执行某些操作,ngOnChanges则可以实现该方法。


推荐阅读