[英]angular6 building a form with child objects
I'm building an angular form that would send data to the server via an API.我正在构建一个 angular 表单,它将通过 API 将数据发送到服务器。 The API is expecting the object in this format API 期望采用这种格式的 object
{
"firstname": "string",
"lastname": "string",
"custom": {
"blood_type": 'string',
}
}
With the current form, I'm building I get this in the console使用当前形式,我正在构建我在控制台中得到它
{
"firstname": "string",
"lastname": "string",
"blood_type": 'string',
}
How do I build my form so it matches the way the API is expecting it?如何构建我的表单以使其符合 API 的预期方式? Below is the form builder script以下是表单构建器脚本
this.testForm = this.formBuilder.group({
firstname: ['', Validators.required],
lastname: ['', Validators.required],
blood_type: ['', Validators.required]
});
HTML HTML
<form [formGroup]="testForm">
<input type="text" class="form-control" formControlName="firstname">
<input type="text" class="form-control" formControlName="lastname">
<input type="text" class="form-control" formControlName="blood_group">
</form>
You can create a custom
formGroup like this:您可以像这样创建custom
表单组:
export class AppComponent {
custom = this.fb.group({ // `custom` formGroup
blood_type: ['', Validators.required]
});
f = this.fb.group({ // Main formGroup
firstname: ['', Validators.required],
lastname: ['', Validators.required],
custom: this.custom // Register the `custom` formGroup here
});
constructor(private fb: FormBuilder) {}
validate() {
console.log(this.f.value);
}
}
And your template could look like this:您的模板可能如下所示:
<form [formGroup]="f">
<input formControlName="firstname">
<input formControlName="lastname">
</form>
<form [formGroup]="custom">
<input formControlName="blood_type">
</form>
<button type="submit" (click)="validate()">OK</button>
<pre>{{f.value | json}}</pre>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.