Hi, I have a parent component with a list, when selecting the selected element is passed to the child component (a form) defined with the @input decorator .
The problem When I modify a property in the form, the change is replicated in the list
I hope that the change is replicated once I press submit
The code
father.html
<div class="container">
<h2>Project List</h2>
<button (click)="expandForm(true)" class="btn btn-default">New</button>
<table class="table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Description</th>
<th>State</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let project of projects" (click)="onSelect(project)">
<td>{{project.name}}</td>
<td>{{project.description}}</td>
<td>{{project.state.description}}</td>
</tr>
</tbody>
</table>
<!--</div>-->
</div>
<project-form [project]="selectedProject">
child component
export class FormComponent implements OnInit {
@Input()
project: Project;
constructor(private service: PService) { }
ngOnInit() {
}
}
child.html
<form (ngSubmit)="onSubmit()" #projectForm="ngForm" *ngIf="_project != null">
<div class="form-group">
<label for="txtName">Name</label>
<input [(ngModel)]="project.name" type="text" class="form-control" id="txtName" name="Name"/>
</div>
<div class="form-group">
<label for="txtDescription">Description</label>
<input [(ngModel)]="_project.description" type="text" class="form-control" id="txtDescription" name="Description"/>
</div>
<div class="form-group">
<label for="ddlState">State</label>
<select [(ngModel)]="project.state" class="form-control" id="ddlState" name="State">
<option *ngFor="let s of projectStates" [ngValue]="s">{{s.description}}</option>
</select>
</div>
<button type="submit" class="btn btn-success">Submit</button>
<button type="reset" (click)="clear()" class="btn btn-default">Cancel</button>
</form>
Create a local object on the form (projectAttachedToForm), which will be of the same type and will be bound to the form, but you still pass the input to the form.
When you press submit and everything is ok, you do the following:
And it should work perfectly for you.
As an improvement, I would recommend you to create a controlled output event in the parent, and leave the form component only for presentation and the parent, as smart, and so when you save data or edit and save in the DB, you always do it from the Smart component.
EDIT
To edit the object in the form, you would have to set the objects, but not passing the reference as indicated above, for this, you would have to clone the object without passing its reference. Something like this:
You can also try JSON.stringify and JSON.parse.