【问题标题】:Angular nested component and reactive forms updating data modelAngular 嵌套组件和响应式表单更新数据模型
【发布时间】:2018-09-11 14:30:19
【问题描述】:

问题是在我的表单中更新值然后选择按钮再次显示表单后,有时值会在那里。 我尝试使用 BehaviorSubject 以不同的方式执行此操作,并使用 EventEmitter 执行此操作。任何帮助将不胜感激。

我已附上plunker:Plunker

以下是我的 plunker 示例的数据。

  this.units = [
  { 
    id: 1, 
    name: "Unit 1", 
    alarms: [
      { 
        name: "Alarm 1",
        description: ""
      },
      { 
        name: "Alarm 2",
        description: ""
      }
    ]
  },
  { 
    id: 2, 
    name: "Unit 2", 
    alarms: [
      { 
        name: "Alarm 1",
        description: ""
      },
      { 
        name: "Alarm 2",
        description: ""
      },
      { 
        name: "Alarm 3",
        description: ""
      }
    ]
  }
];

用户选择单元 1 按钮并更新第一个警报的描述属性。 用户点击 Unit 2 按钮,数据通过调用 this.updateData(changedProp.previousValue); 保存到 ngOnChange 中的集合 当用户单击按钮 Unit 1 时,第一个警报描述中更改的值并不总是存在。

我也不确定是否有更好的方法。

任何帮助将不胜感激。

【问题讨论】:

  • 我有一个 github 链接,指向我尝试使用 BehaviorSubject 的链接:github.com/GertB1/test-forms
  • 使用以前的值不是保存单位的好主意
  • 嗨,Yerkon。我正在使用之前的值来获取我想要更新的单元的 ID。然后我使用表单提取更改的值。
  • 如果我添加一个保存按钮并删除 this.updateData(changedProp.previousValue);从 ngOnChanges 然后它按预期工作。有没有不用保存按钮自动保存的方法?不知道有没有可以使用的生命周期钩子?
  • 我可以解决你的问题,但稍后✌

标签: angular angular-components angular-reactive-forms


【解决方案1】:

Get access to child UnitEdit component from parent and when select the tab, call this.unitComp.updateData(unit) method from parent to save unit state:

export class App {
  units: Unit[];
  unit: Unit = null;
  constructor(private unitService: UnitService) {
  }

    @ViewChild(UnitEditComponent)
  private unitComp: UnitEditComponent;

  ...

  unitSelected(unit: Unit) {
    this.unitComp.updateData(this.unit);
    // save unit states
    console.log(this.unitComp)
    this.unit = unit;
  }
}

如果您需要有关 @ViewChild 装饰器的更多详细信息,请查看 Parent calls an @ViewChild()

Plunker EXAMPLE

【讨论】:

  • 感谢Yerkon,您肯定是大师。
猜你喜欢
  • 2018-07-14
  • 1970-01-01
  • 2018-06-22
  • 1970-01-01
  • 2017-01-30
  • 1970-01-01
  • 2018-07-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多