Compare groups with each other我是angular的新手,我正在尝试使用动态json构建表单。我已经建立了一个表格,在验证该表格时遇到了一些问题。我已附上json和代码以供参考,任何帮助将不胜枚举。预先感谢
json文件
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="react"></div>
打字稿文件
{ "form" : [
{
"key": "role_name",
"label": "Role Name",
"type": "text",
"value": "",
"required": true,
"order": 1,
"validationMessage":"Role Name is required"
},
{
"key": "brave",
"label": "Bravery Rating",
"type": "dropdown",
"options": [
{"key": "solid", "value": "Solid"},
{"key": "great", "value": "Great"},
{"key": "good", "value": "Good"},
{"key": "unproven", "value": "Unproven"}
],
"required": true,
"order": 5,
"validationMessage":"Bravery Rating is required"
},
{
"key": "comments",
"label": "comments",
"type": "textarea",
"value": "",
"required": false,
"order": 6,
"validationMessage":null
},
{
"key": "last_name",
"label": "Last Name",
"type": "text",
"value": "",
"required": false,
"order": 2,
"validationMessage":null
},
{
"key": "gender",
"label": "Gender",
"type": "radio",
"value": "",
"options": [
{"key": "male", "value": "Male"},
{"key": "female", "value": "Female"}
],
"required": true,
"order": 3,
"validationMessage":"Gender is required"
},
{
"key": "dateOfBirth",
"label": "Date of birth",
"type": "calender",
"value": "",
"required": true,
"order": 4,
"validationMessage":"Date of birth is required"
}
]}
}
html文件
import { Component } from '@angular/core';
import { FormGroup,FormControl } from '@angular/forms';
import { form } from '../assets/form.json';
import { Validators } from '@angular/forms'
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
title = 'my-app';
formjson = form
userDetails:object;
click():void{
console.log(typeof(form));
console.log(this.userDetails['value']);
}
ngOnInit(){
this.formjson.sort((a,b) =>
a.order - b.order
)
this.userDetails = new FormGroup({
role_name : new FormControl(this.userDetails['name'],[Validators.required]),
brave : new FormControl(''),
comments : new FormControl(''),
last_name : new FormControl(''),
gender : new FormControl(''),
dateOfBirth : new FormControl('')
});
}
请帮助我确定这是正确的实现方式还是其他任何好的方法。
答案 0 :(得分:1)
您正在role_name
变量中使用,在打字稿文件中任何位置的HTML文件中许多未定义的位置,
我了解到您正在尝试访问role_name
表单控件,因此可以在打字稿文件中设置一个这样的getter,它将返回role_name
表单控件
export class AppComponent {
title = 'my-app';
formjson = form
userDetails:object;
/** Define your FormGroup here, You have given the same name for, FormGroup and
UserDetails variable, which is not correct
*/
userDetailsForm: FormGroup;
/** define the getter here, before the constructor gets called */
get role_name() {
return this.userDetailsForm.get('role_name');
}
}
注意:也在HTML文件中将userDetails
更改为userDetailsForm