Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/33.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 如何为非必需的FormGroup定义必需的FormControl?_Angular_Typescript_Angular Forms - Fatal编程技术网

Angular 如何为非必需的FormGroup定义必需的FormControl?

Angular 如何为非必需的FormGroup定义必需的FormControl?,angular,typescript,angular-forms,Angular,Typescript,Angular Forms,在我的应用程序中,我有一个表单组,不需要提交表单,但是,如果用户试图填写该组的任何部分,则需要在其中显示特定字段,否则该组将被视为无效 是否有一种方法可以为非必需的FormGroup定义必填字段,从而保证数据的完整性 这是我的小组 FormGroup({ officeId: new FormControl("", [Validators.required]), fileOwner: fileOwner, secondaryOwner: secondaryOwner,

在我的应用程序中,我有一个
表单组
,不需要提交表单,但是,如果用户试图填写该组的任何部分,则需要在其中显示特定字段,否则该组将被视为无效

是否有一种方法可以为非必需的
FormGroup
定义必填字段,从而保证数据的完整性

这是我的小组

FormGroup({
    officeId: new FormControl("", [Validators.required]),
    fileOwner: fileOwner,
    secondaryOwner: secondaryOwner,
    managedByPrimary: new FormControl(true, [Validators.required])
});
这是我的
文件所有者
表单组
,我已将其标记为
必需的

let fileOwner: FormGroup = new FormGroup({
    FirstName: new FormControl("", [Validators.required]),
    LastName: new FormControl("", [Validators.required]),
    IdentificationNumber: new FormControl("", [Validators.required]),
    PhoneNumber: new FormControl(""),
    EmailAddress: new FormControl("")
}, [Validators.required]);
在这里,我试图或多或少地说,提交表单需要这个组,而在这个组中,
FirstName
LastName
IdentificationNumber
是必需的

SecondaryOwner
紧随其后,因为它是具有不同验证要求的相同模型

let secondaryOwner: FormGroup = new FormGroup({
    FirstName: new FormControl("", [Validators.required]),
    LastName: new FormControl("", [Validators.required]),
    IdentificationNumber: new FormControl("", [Validators.required]),
    PhoneNumber: new FormControl(""),
    EmailAddress: new FormControl("")
});
在这里,我没有要求该组是必需的,但指出了特定字段是必需的。我的意图是多多少少地说,“这个组不是必需的,但如果您填写了它,这些是该组被视为有效的必要字段”


我将如何完成这种行为?现在,
SecondaryOwner
实例化为
Invalid
,这很有意义。但本质上,除非它的任何一个控件变脏,否则我不希望它被考虑用于验证。

我建议动态更新表单。使形式要求的状态受到其他事物的影响。以下是一些想法:

  • 在没有所需验证器的情况下启动表单,并侦听表单事件“dirty”或向表单添加单击事件,当用户单击它时,将表单验证器更改为“required”

  • 添加一个单独的输入或按钮,用户可以单击该按钮说“是的,我想填写此表单”或您喜欢的任何内容,然后如果用户决定填写表单,您可以在表单上添加ngIf。或者,您可以像上面那样处理所需的验证器,但使用此外部输入

  • 如果您只想在用户实际输入数据时才需要表单,请在更改事件中侦听表单值。添加值后,将表单更新为required

  • 在这两种情况下,表单所需的函数可能如下所示:

    requireForm() {
        this.myForm.setValidators(Validators.required)
    }
    
    你也可以退房