我正在嘗試同時獲取多個表單的結果...目前,我有一個結構可以逐個獲取結果,但我需要發送所有表單的結果...
我的html代碼:
<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>
我試圖將按鈕放在方法之外,但它不起作用,而且我試圖通過 ngModel 獲取值,但它也不起作用。
你有什么建議嗎?
uj5u.com熱心網友回復:
當你在回圈中有一個模板參考變數時,當你使用這個變數時,每次迭代都是“作用域”的。
您可以使用 ViewChildren 獲取具有相同“模板參考變數”的所有元素
@ViewChildren('f') forms:QueryList<NgForm>
回圈外的按鈕型別提交可以呼叫函式(您可以呼叫提交或以其他方式)
<button (click)="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)
})
}
}
現在我們得到表格,問題是:如何創建資料?
//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}
})
}
順便說一句,您可能想看看使用陣列或ReactiveForms來使用[(ngModel)]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/497730.html