Issue
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 class="title-card">
<span>{{x.name}}</span>
</mat-card-title>
<mat-card-content *ngFor="let param of x.modelParameter; index as i">
<div class="param-title">
<span><b>{{param.name}}</b></span>
</div>
<div class="set-slider" *ngIf="param.type === 'continuous'">
<label class="gridSizeValue"><b>{{param.values_arr[0]}}</b></label>
<mat-slider #gridsize (change)="updateSetting($event)" class="slider" thumbLabel
tickInterval="1" [displayWith]="formatLabel" min="{{param.values_arr[0]}}"
max="{{param.values_arr[1]}}" aria-label="units" class="form-control" ngModel name="{{param.name}}">
</mat-slider>
<label class="gridSizeValue"><b>{{param.values_arr[1]}}</b></label>
</div>
<div class="set-categorical" *ngIf="param.type === 'categorical'">
<mat-form-field appearance="outline">
<mat-select
class="form-control"
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" class="save-button">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?
Solution
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
Answered By - Eliseo
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.