代码之家  ›  专栏  ›  技术社区  ›  rmcknst2

Angular14如何遍历严格类型的FormGroups控件

  •  0
  • rmcknst2  · 技术社区  · 1 年前

    我正在使用Angular v14,并将我的formGroups升级为严格类型。我有一个逻辑块,如果执行,它将遍历FormGroup的所有控件,并执行 有些东西——这部分并不重要,因为我甚至无法进入这部分

    以下是我尝试过的:

    表单设置

    export interface ExampleForm{
        q1 : FormControl<string | null>,
        q2: FormControl<string | null>,
        q3: FormControl<string | null>,
        ...
    }
    
    ...
    
    exampleForm= this.fb.group<ExampleForm>({
        q1 : new FormControl('',[Validators.required,]),
        q2 : new FormControl('',[Validators.required,]),
        q3 : new FormControl('',[Validators.required,]),
      })
    //the form is much longer but shortening for example purposes
    
    ...
    

    此处出现逻辑中断

    ngOnInit(): void {
        if (someLogic) {
          Object.keys(this.exampleForm.controls).forEach((key) => {
            this.exampleForm.controls[key].setValue("some value");
            //other logic here using key
          });
        }
      }
    

    收到错误:

    元素隐式具有“any”类型,因为类型为“string”的表达式不能用于索引类型“{q1:FormControl<string|null>;q2:FormControl<string| null<;q3:FormControl&llt;stringe|null>”;;

    我所尝试的:

    if (someLogic) {
          Object.keys(this.exampleForm.controls).forEach((key:string) => {
            this.exampleForm.controls[key].setValue("some value");
            //other logic here using key
          });
        }
    
    ...
    
    if (someLogic) {
          Object.keys(this.exampleForm.controls).forEach((key : string | null) => {
            this.exampleForm.controls[key].setValue("some value");
            //other logic here using key
          });
        }
    //with this the above error goes away but instead I get a new one saying Type 'null' cannot be used as an index type.
    

    此外,由于其他原因,我需要在这些组上使用forEach块,而不仅仅是设置一个值 补丁值() 这还不够。

    1 回复  |  直到 1 年前
        1
  •  1
  •   Mike Jerred    1 年前

    我认为问题在于表单有密钥 q1 , q2 , q3 ,等等,但您正试图用 string 。试试这个:

    for (const [key, control] of Object.entries(this.exampleForm.controls)) {
      control.setValue('some value');
      // ...
    }
    

    因为编译器知道 this.exampleForm.controls 看起来是这样的:

    {
      q1: ...,
      q2: ...,
      q3: ...
    }
    

    仅类型中的键 'q1' | 'q2' | 'q3' 保证在用于索引时具有一个值。