Reputation: 77
In a Angular 7 and ReactiveForm, if i put a file in <input type="file">
, and i add a row with formgroup.addControl()
, all the <input type="file">
are reset.
I'm stuck because type="file"
can't be again init, with a personal fonction, because they must be init with a string null value.
Stackblitz: https://stackblitz.com/edit/angular-yvk6nb
I need to keep the type="file"
values when i add rows with addControl
Upvotes: 1
Views: 727
Reputation: 73367
You form structure is off. If you were to put <pre>{{formgroup.value | json}}</pre>
in your stackblitz, you would see that the structure is not correct and is causing you issues.
This seems like a perfect use of a FormArray
instead, so that is what I would suggest:
myForm: FormGroup;
constructor(private formBuilder: FormBuilder) { }
ngOnInit() {
// wrap the formarray inside a formgroup
this.myForm = this.formBuilder.group({
files: this.formBuilder.array([
this.initRow()
])
})
}
// called when adding a new row
addRow() {
(<FormArray>this.myForm.get('files')).push(this.initRow());
}
// creates and returns a new formgroup
initRow() {
const blanckForm = this.formBuilder.group({
name: [''],
file: ''
});
return blanckForm;
}
And your template would look like:
<form [formGroup]="myForm">
<div formArrayName="files">
<div *ngFor="let file of myForm.get('files').controls; let i = index" [formGroupName]="i">
<input formControlName="name" type="text">
<input formControlName="file" type="file">
</div>
</div>
</form>
<input type="button" (click)="addRow()" value="ADD ROW">
Your forked STACKBLITZ
Upvotes: 1