【问题标题】:How to clear previous values from ngOnchanges based on selection in Angular4如何根据Angular4中的选择从ngOnchanges中清除以前的值
【发布时间】:2018-10-16 21:48:08
【问题描述】:

在我的应用程序组件中,我有一个手风琴,用户选择的菜单的 ID 将通过使用 ngOnChanges 传递给子组件,从子组件调用基于应用程序组件选择的菜单 ID 的 API。

手风琴结构类别、组、子组

我要做的是,当用户选择一个类别、组和子组时,该 Id 被传递给子组件并且 API 也被调用。

让我们假设第一个选择的 ID 分别为 (100,101,102)

现在用户选择了同一类别下的另一个组,现在通过传递错误的 ID (100,200,102) 调用 API,这里用户没有选择任何子组,但该值取自之前的值。

那么我该怎么做以下

  • 1、用户选择新组时清除子组值。
  • 2,当用户选择新的Category时清除组值。

Stackblitz 文件:

https://stackblitz.com/edit/angular-bootstrap-carousel-dynamic2-exbr5f?file=app%2Fchild%2Fchild.component.ts

编辑:

ngOnChanges(changes: SimpleChanges) {

    if (changes['C_code'].currentValue != "") {
      this.a = changes['C_code'].currentValue ;
      if (this.a != changes['C_code'].previousValue) {
        this.G_code = "";
        this.SG_code = "";
      }
    }

    if (changes['G_code'].currentValue != "") {
      this.b = (changes['G_code'].currentValue);
      if (this.b != changes['G_code'].previousValue) {
        this.SG_code = "";
      }
    }

  }

Stackblitz 文件:

https://stackblitz.com/edit/angular-bootstrap-carousel-dynamic2-9i1xzr?file=app/child/child.component.ts

【问题讨论】:

    标签: angular typescript ngonchanges


    【解决方案1】:

    您可以在 AppComponent 中执行此操作,方法是在事件挂钩中将相应的值设置回 null/empty,如下所示:

    changeGroupCode(event: any) {
        this.groupCode = event;
        this.subGroupCode = null;
    }
    

    然后在您的子组件中,在调用 API 之前检查每个值的 null/空字符串。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-02-09
      • 2015-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多