在Angular表单中添加动态控件失败。

huangapple go评论68阅读模式
英文:

Adding dynamic controls in an Angular form fails

问题

I am spending too much time on something that should be simpler, and I don't get where the mistake is. I just try to add some dynamic inputs controls to a form but it fails with the error Cannot find control with name: '0'. I put an example here: Stackblitz demo


Name


{{formControls['dependentNameControl'].hasError('minlength') ? "Min 2 chars":""}}
{{formControls['dependentNameControl'].hasError('maxlength') ? "Max 50 chars":""}}

import { Component } from '@angular/core';
import {
FormArray,
FormBuilder,
FormControl,
FormGroup,
Validators,
} from '@angular/forms';

@Component({
selector: 'example',
templateUrl: 'example.html',
})
export class Example {
public form!: FormGroup;

constructor(private formBuilder: FormBuilder) {}

ngOnInit(): void {
this.form = this.formBuilder.group({
dependentsControls: new FormArray([]),
});
}

get formControls() {
return this form controls.
}

dependentsControls(): FormArray {
return this.form.controls['dependentsControls'];
}

public createDependent() {
return this.formBuilder group({
dependentNameControl: new FormControl<string | undefined>('', [
Validators.minLength(2),
Validators.maxLength(50),
]),
});
}

public onAddDependent(): void {
this dependentsControls push(this createDependent).
console.log(this dependentsControls controls.
}
}

Copyright 2022 Google LLC. All Rights Reserved.
Use of this source code is governed by an MIT-style license that can be found in the LICENSE file at https://angular.io/license.

英文:

I am spending to much time on something that should be simpler and I don't get it where is the mistake. I just try to add some dynamic inputs controls to a form but it fails with error Cannot find control with name: &#39;0&#39;. I put an example here:
Stackblitz demo

&lt;form [formGroup]=&quot;form&quot;  class=&quot;top15x2&quot; autocomplete=&quot;off&quot;&gt;

&lt;div class=&quot;w-100  text-start&quot;&gt;
&lt;button type=&#39;button&#39; mat-button (click)=&quot;onAddDependent()&quot; class=&quot;button-submit&quot; style=&quot;width:150px&quot;&gt;+ Add Dependent&lt;/button&gt;
&lt;/div&gt;


&lt;div
  *ngFor=&quot;let dependentsGroup of this.dependentsControls().controls let i=index&quot;
  [formGroupName]=&quot;i&quot;&gt;
  
  &lt;div class=&quot;d-flex flex-row w-100 justify-content-start gap20&quot;&gt;
    &lt;div class=&quot;col-2&quot;&gt;
      &lt;mat-form-field class=&quot;w-100&quot;&gt;
        &lt;mat-label&gt;Name &lt;/mat-label&gt;
        &lt;input matInput formControlName=&quot;dependentNameControl&quot; /&gt;
        &lt;mat-error *ngIf=&quot;formControls[&#39;dependentNameControl&#39;].invalid&quot;&gt;
          {{formControls[&#39;dependentNameControl&#39;].hasError(&#39;minlength&#39;) ? &quot;Min 2
          chars&quot;:&quot;&quot;}}
          {{formControls[&#39;dependentNameControl&#39;].hasError(&#39;maxlength&#39;) ? &quot;Max 50
          chars&quot;:&quot;&quot;}}
        &lt;/mat-error&gt;
      &lt;/mat-form-field&gt;
    &lt;/div&gt;
  &lt;/div&gt;
&lt;/div&gt;


&lt;/form&gt;

<!-->

import { Component } from &#39;@angular/core&#39;;
import {
  FormArray,
  FormBuilder,
  FormControl,
  FormGroup,
  Validators,
} from &#39;@angular/forms&#39;;

/** @title Basic datepicker */
@Component({
  selector: &#39;example&#39;,
  templateUrl: &#39;example.html&#39;,
})
export class Example {
  public form!: FormGroup;

  constructor(private formBuilder: FormBuilder) {}

  ngOnInit(): void {
    this.form = this.formBuilder.group({
      dependentsControls: new FormArray([]),
    });
  } //ngOnInit

  get formControls() {
    return this.form.controls;
  }

  dependentsControls(): FormArray {
    return &lt;FormArray&gt;this.form.controls[&#39;dependentsControls&#39;];
  }

  public createDependent() {
    return this.formBuilder.group({
      dependentNameControl: new FormControl&lt;string | undefined&gt;(&#39;&#39;, [
        Validators.minLength(2),
        Validators.maxLength(50),
      ]),
    });
  }

  public onAddDependent(): void {
    this.dependentsControls().push(this.createDependent());
    console.log(this.dependentsControls().controls);
  }
}

/**  Copyright 2022 Google LLC. All Rights Reserved.
    Use of this source code is governed by an MIT-style license that
    can be found in the LICENSE file at https://angular.io/license */

答案1

得分: 2

formArrayName添加进去,并且将动态组的控制引用更改如下:

尝试这样做:

<div formArrayName="dependentsControls">
  <div *ngFor="let dependentsGroup of this.dependentsControls().controls; let i = index" [formGroupName]="i">
    <!-- ... -->
    <mat-error *ngIf="dependentsGroup.get('dependentNameControl')?.invalid">
      {{ dependentsGroup.get('dependentNameControl')?.hasError('minlength') ? "最少2个字符" : "" }}
      {{ dependentsGroup.get('dependentNameControl')?.hasError('maxlength') ? "最多50个字符" : "" }}
    </mat-error>
  </mat-form-field>
</div>
</div>

Stackblitz

英文:

You need to add formArrayName, and also change controls reference to each dynamic group:

Try this:

 &lt;div formArrayName=&quot;dependentsControls&quot;&gt;
    &lt;div
      *ngFor=&quot;let dependentsGroup of this.dependentsControls().controls let i=index&quot;
      [formGroupName]=&quot;i&quot;
    &gt;
     ...
            &lt;mat-error
              *ngIf=&quot;dependentsGroup.get(&#39;dependentNameControl&#39;)?.invalid&quot;
            &gt;
              {{dependentsGroup.get(&#39;dependentNameControl&#39;)?.hasError(&#39;minlength&#39;)
              ? &quot;Min 2 chars&quot;:&quot;&quot;}}
              {{dependentsGroup.get(&#39;dependentNameControl&#39;)?.hasError(&#39;maxlength&#39;)
              ? &quot;Max 50 chars&quot;:&quot;&quot;}}
            &lt;/mat-error&gt;
          &lt;/mat-form-field&gt;
        &lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;
  &lt;/div&gt;

Stackblitz

huangapple
  • 本文由 发表于 2023年3月31日 17:41:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/75897006.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定