I'm trying to get the result for multiples forms at same time... Currently, I have a structure to get the result one by one but I need to send the result of all of them...
My html code:
<form (ngSubmit)="onSubmit(f)" #f="ngForm" *ngFor="let x of selectedValue; index as i">
<mat-card >
<mat-card-title >
<span>{{x.name}}</span>
</mat-card-title>
<mat-card-content *ngFor="let param of x.modelParameter; index as i">
<div >
<span><b>{{param.name}}</b></span>
</div>
<div *ngIf="param.type === 'continuous'">
<label ><b>{{param.values_arr[0]}}</b></label>
<mat-slider #gridsize (change)="updateSetting($event)" thumbLabel
tickInterval="1" [displayWith]="formatLabel" min="{{param.values_arr[0]}}"
max="{{param.values_arr[1]}}" aria-label="units" ngModel name="{{param.name}}">
</mat-slider>
<label ><b>{{param.values_arr[1]}}</b></label>
</div>
<div *ngIf="param.type === 'categorical'">
<mat-form-field appearance="outline">
<mat-select
ngModel name="option">
<mat-option *ngFor="let op of param.values_arr" [value]="op">
{{op}}
</mat-option>
</mat-select>
</mat-form-field>
</div>
</mat-card-content>
</mat-card>
<button mat-raised-button type="submit" >Send Models</button>
</form>
I was trying to put the button outside method but it does not work, and also I was trying to get the value by ngModel but it does not works neither.
Do you have any suggest?
CodePudding user response:
When you has a template reference variable in a loop, when you use this variable is "scoped" to each iteration.
You can use ViewChildren to get all elements with the same "template reference Variable"
@ViewChildren('f') forms:QueryList<NgForm>
A button type submit outside the loop can call to a function (you can call submit or in another way)
<button (click)="submit()">
You function submit
submit()
{
const isInvalid=this.forms.map(x=>x.valid).find(x=>!x)
//isInvalid is "undefined" if all are valid
// is true if one of the forms is invalid
if (!isInvalid)
{
this.forms.forEach(x=>{
console.log(x.value)
})
}
}
Now we get the forms the question is: how you can create your data?
//in array
submit()
{
...
const data=this.forms.map(x=>x.value)
}
//in an object
submit()
{
...
const obj:any={}
this.forms.forEach((x,i)=>{
obj['form' i]=x.value
})
}
//if the "name" of the controls are all differents
//using spread operator
submit()
{
...
let obj:any={}
this.forms.forEach((x,i)=>{
obj={...obj,...x.value}
})
}
BTW perhafs you want to take a look to use [(ngModel)] using an array or ReactiveForms