【问题标题】:Form value with json data in ng-model format带有 ng-model 格式的 json 数据的表单值
【发布时间】:2017-07-25 03:06:44
【问题描述】:

我的 html 中有一个表单元素。

 <form [formGroup]="myForm" (ngSubmit)="searchIncident()">
    <select  class="form-control"
            id="category"
            (change)="getSubCategories($event.target.value)"
            (ngModel)="categoryMast.catCode"
            formControlName="catCode">
            <option value="select" selected disabled>--Select--</option>
            <option *ngFor="let category of categoryMaster" value="{{category.catCode}}">{{category.catDesc}}</option>
    </select> 
 </form>

下面是我的打字稿。

export class ISearchComponent {
    myForm: FormGroup;

    constructor(private masterDataService:MasterDataService,private http: Http) { // MasterDataService is defined already
        this.myForm = new FormGroup({
        'catCode'   : new FormControl(),

     });

}    

//THis is the search Incident method which makes the server call
searchIncident(){
    let headers: Headers = new Headers();
    headers.set("Content-Type", "application/json");

    this.http.post(AppUtils.INCIDENT_SEARCH, this.myForm.value, {headers: headers}).subscribe(res=>{
             this.rowData = res.json().result;
         }, err=>{             
         });

    }
}

这里提交的json是(this.myForm.value)

{
"cateCode":12
}

但我需要它在 ng-model 中定义的方式

 "categoryMast": {
    "catCode": 12
  }

尝试过的解决方案:

一个解决方案是我需要修改 json 以便我可以添加 categoryMast 数组,但这会变得很麻烦,因为会有更多这样的字段。

【问题讨论】:

  • 那么您必须在 http post 调用之前从发布的数据创建自定义 json。
  • 这就是我在尝试解决方案中提到的。
  • 你在通过this.myForm.value,你试过this.categoryMast吗?
  • 需要在表单中传递其他值,这里我已经截断了表单
  • 那你需要什么?它应该是什么?

标签: angular angular2-forms angular2-services


【解决方案1】:

我可能实际上会像构建模型一样构建表单,因此您最终会得到与您想要的完全一样的表单值。根据您的模型,这将非常复杂,如果对模型进行更改,可能很难维护。 (另一个可行的选择是将表单中的值转换为模型,然后再将其发送到 api,如 cmets 中建议的那样)。

由于您使用的是表单,因此您可以废弃所有ngModel,这就是您可以使用表单控件的目的:)

因此,根据您当前的设置,您的表单将如下所示:

this.myForm = this.fb.group({
  categoryMast: this.fb.group({
    catCode: ['']
  })
});

还有你的html:

<form [formGroup]="myForm">
<label>Category: </label>
<div formGroupName="categoryMast">
  <select formControlName="catCode">
    <option value="select" selected disabled>--Select--</option>
    <option *ngFor="let category of categoryMaster" value="{{category.catCode}}">{{category.catDesc}}</option>
  </select>
</div>
</form>

这将给出您正在寻找的对象:

{
  "categoryMast": {
    "catCode": ""
  }
}

Demo Plunker

【讨论】:

    猜你喜欢
    • 2016-11-29
    • 1970-01-01
    • 2017-11-01
    • 1970-01-01
    • 2015-05-05
    • 2015-08-13
    • 2018-12-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多