问题
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