我有类似的需求,这是一种解决方法:
this.form = new FormGroup({
'name': new FormControl(null, Validators.required),
'description': new FormControl(null),
'connection': new FormGroup({
'url': new FormControl(null),
'authentification': new FormGroup({
'username': new FormControl(null, Validators.minLength(5)),
'password': new FormControl(null),
}, this.authentificationValidator.bind(this)),
}, this.connectionValidator.bind(this))
});
2个验证器功能:
authentificationValidator(g: FormGroup): any {
const username = g.get('username').value;
const password = g.get('password').value;
if( (username && !password) || (!username && password) ) {
return {
authentification: true
};
}
}
connectionValidator(g: FormGroup): any {
const url = g.get('url').value;
const authentification = g.get('authentification');
const username = authentification.get('username').value;
const password = authentification.get('password').value;
if( (username || password) && !url ) {
return {
connection: true
};
}
}
对于输出,如果您只填写名称,您仍然会有:
{
"name": null,
"description": null,
"connection": {
"url": null,
"authentification": {
"username": null,
"password": null
}
}
}
所以你必须有条件地创建一个新对象才能拥有:
{
"name": null,
"description": null,
"connection": null
}
检查这个 plunker 来试验这个解决方案