Angular nested component and reactive forms updating data model

荒凉一梦 提交于 2019-12-11 16:13:59

问题


The problem is that after updating values in my form and then selecting the button to display the form again the values are sometimes there. I have tried to do this in different ways using a BehaviorSubject and also doing it with the EventEmitter. Any help would be appreciated.

I have attached the plunker: Plunker

Below is the data for my plunker example.

  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: ""
      }
    ]
  }
];

The user selects Unit 1 button and updates the description property of the first Alarm. The user clicks on the Unit 2 button and the data is save to the collection in the ngOnChange with the call to this.updateData(changedProp.previousValue); When the user click on button Unit 1 the value changed in the description of the first alarm is not always there.

I am also not sure if there is a better way of doing this.

Any help would be appreciated.


回答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;
  }
}

If you need more detail about @ViewChild decorator look at Parent calls an @ViewChild()

Plunker EXAMPLE



来源:https://stackoverflow.com/questions/49610159/angular-nested-component-and-reactive-forms-updating-data-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!