【问题标题】:Angular data communication to and from components与组件之间的角度数据通信
【发布时间】:2017-11-14 21:20:38
【问题描述】:

我有一个父组件(P1)和两个子组件(C1 和 C2)。 两个子组件都有一个可编辑的primeng 数据表。 我在 P1 上有两个按钮:fetch() 和 save()fetch() 调用数据库来获取数据。 我正在使用共享服务来获取数据并将其传递给使用 BehaviorSubject 的组件。 我的数据对象如下所示:

export interface ParentObj { name: string; child1 : Child1[]; child2: Child2[]}
export interface Child1 { weight: number;}
export interface Child2 { code: string;}

子组件从共享服务订阅数据。 现在的问题是子组件也修改了它们拥有的数据。 因此,单击 P1 上的 save() 时,我无法从子组件中获取最新修改的值,因为我无法通知 P1 C1 和/或 C2 已更改数据。

有没有办法实现相同的功能,以便在调用 save() 并反映在 ParentObj 中时通知子组件?。 p>

【问题讨论】:

  • @Manu:数据已经从父级传递给子级,但不是相反,因为没有像子级组件上的事件这样的通信方式。
  • 你应该尝试使用 RxJS 库中的行为主题
  • 尝试使用 redux ngrx-store 进行状态管理和数据共享。

标签: angular typescript primeng primeng-datatable


【解决方案1】:

您可以为此目的使用事件发射器,这在从子组件到父组件通信时最有用。

例子:-

P1 组件:-

<c1 (notifyParent)="notify(data)"></c1>
<c2 (notifyParent)="notify(data)"></c1>

notify(data) {
    console.log(data); //notify parent
}

C1组件:-

@Output() notifyParent= new EventEmitter();

然后

this.notifyParent.emit(data) //or notify with true value

C2组件:-

@Output() notifyParent= new EventEmitter();

然后

this.notifParent.emit(data) //or notify with true value

【讨论】:

    【解决方案2】:

    我能够使用来自'@angular/core'ViewChild 解决它,因为子组件上没有事件触发器。 父级可以使用@ViewChild(ChildComponent) child; 读取子级属性 参考:Here

    【讨论】:

      猜你喜欢
      • 2019-10-30
      • 2021-03-11
      • 1970-01-01
      • 1970-01-01
      • 2019-09-11
      • 2020-09-12
      • 2019-05-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多