我有一个表单(模板驱动),有两个字段和一个切换字段值的按钮。
字段的名称为data[0]
,data[1]
的值为france
和usa
。
当我点击切换按钮时,模板会按预期在data[0]
和data[1]
中的法国呈现美国。当我提交表单时,我有data[0]=france
和data[1]=usa
。
预期行为:
我希望表单与模板呈现的值相同,因此data[0]=usa
和data[1]=france
。
//our root app component
import {Component, NgModule, OnInit, VERSION} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
import { FormsModule, ReactiveFormsModule } from '@angular/forms'
@Component({
selector: 'my-app',
template: `
<div>
<my-form></my-form>
</div>
`,
})
export class App {
name:string;
constructor() {
this.name = `Angular! v${VERSION.full}`
}
}
@Component({
selector: 'my-form',
template: `
<h2>Switch input value and check or submit</h2>
<form #myForm="ngForm" (ngSubmit)="onsubmit($event, myForm)">
<div *ngFor="let country of countries; let i = index">
<input [ngModel]="country" name="data[{{i}}]" />
</div>
<button (click)="switch(myForm)">switch</button> <button (click)="switchAndPatch(myForm)">switch & patch</button> <br />
<button (click)="checkOrder($event, myForm)" type="button">checkOrder</button>
<button type="submit">submit</button>
</form>
<h2>List of countries that should be in same order than input</h2>
<ol>
<li *ngFor="let formCountry of formCountries; let i = index">field {{formCountry.fieldName}}: <strong>{{formCountry.label}}</strong></li>
</ol>
`,
})
export class FormComponent implements OnInit{
countries = ['france', 'usa'];
formCountries = []
constructor() {
this.name = `Angular! v${VERSION.full}`
}
ngOnInit() {
this.formCountries = []
this.countries.forEach((country: string, i: number) => {
this.formCountries[i] = {label: country, fieldName: `data[${i}]`}
}
}
switch(form: NgForm){
this.countries.reverse()
}
switchAndPatch(form: NgForm){
this.switch(form)
this.countries.forEach((country: string, i: number) => {
let newFormValues = {}
newFormValues[`data[${i}]`] = country
form.form.patchValue(newFormValues)
})
}
checkOrder(ev, form: NgForm) {
this.formCountries = []
Object.keys(form.value).forEach((key: string, i: number) => {
this.formCountries[i] = {label: form.value[key], fieldName: key}
})
console.log('checkOrder', this.countries, this.formCountries)
}
onsubmit(ev, form) {
this.formCountries = []
Object.keys(form.value).forEach((key: string, i: number) => {
this.formCountries[i] = {label: form.value[key], fieldName: key}
})
console.log('onsubmit', this.countries, this.formCountries)
}
}
@NgModule({
imports: [ FormsModule, ReactiveFormsModule, BrowserModule ],
declarations: [ App, FormComponent ],
bootstrap: [ App ]
})
export class AppModule {}