【问题标题】:Reactive Form says it is invalid when a new FormGroup is added to a FormArray when it is validReactive Form 在有效的情况下将新的FormGroup添加到FormArray时表示无效
【发布时间】:2021-04-11 01:48:00
【问题描述】:

我有用于创建具有三个控件的配方的反应形式:

  • 标题
  • FormGroup 成分的 FormArray,具有两个属性
    • 成分的名称
    • 服用量
  • FormArray 的步骤

我的问题是,每当我将 FormControl 或 FormGroup 添加到 FormArray 时,即使我填写了所有字段,表单的状态也是无效的。如果表单无效,则有一个提交按钮将被禁用。

我的代码:

<h1>Create a recipe</h1>

<form [formGroup]="recipe" (ngSubmit)="onSubmit()" autocomplete="off">
    <div>
        <mat-form-field appearance="outline" color="accent" hideRequiredMarker="true">
            <mat-label>Name</mat-label>
            <input formControlName="title" matInput required type="text" placeholder="ex. Oats Smoothie">
            <mat-error>Name is <strong>required</strong></mat-error>
        </mat-form-field>
    </div>
    <hr>
    <div formArrayName="ingredients">
        <div *ngFor="let control of ingredients.controls; index as i">
            <div [formGroupName]="i">
                <mat-form-field appearance="outline" color="accent" hideRequiredMarker="true">
                    <mat-label>Ingredient name</mat-label>
                    <input formControlName="name" matInput required placeholder="ex. Oats" type="text">
                    <mat-error>Ingredients are
                        <strong>required</strong>
                    </mat-error>
                </mat-form-field>
                <mat-form-field appearance="outline" color="accent" hideRequiredMarker="true">
                    <mat-label>Ingredient amount</mat-label>
                    <input formControlName="amount" matInput type="text" placeholder="ex. 1 cup">
                    <mat-error>Ingredients are
                        <strong>required</strong>
                    </mat-error>
                    <mat-icon matSuffix (click)="removeIngredient(i)" *ngIf="!(ingredients.controls.length == 1)">clear</mat-icon>
                </mat-form-field>
            </div>
        </div>
        <button type="button" mat-raised-button color="primary" (click)="addIngredient()">Add Ingredient</button>
    </div>
    <hr>
    <div formArrayName="steps">
        <mat-form-field *ngFor="let step of steps.controls; index as i" appearance="outline" color="accent"
            hideRequiredMarker="true">
            <mat-label>Steps</mat-label>
            <textarea [formControlName]="i" type="text" matInput placeholder="ex. Take Oats"
                cdkTextareaAutosize></textarea>
            <mat-icon matSuffix (click)="removeStep(i)" *ngIf="!(steps.controls.length == 1)">clear</mat-icon>
            <mat-error>Steps are <strong>required</strong></mat-error>
        </mat-form-field>
        <br>
        <button type="button" (click)="addStep()" mat-raised-button color="primary">Add Step</button>
    </div>
    <br>
    <button type="submit" [disabled]="!recipe.valid" mat-raised-button color="primary">Submit</button>
</form>
  recipe: FormGroup | any;
  constructor(private formBuilder: FormBuilder, private recipeService: RecipesService, private dialog: MatDialog, private router: Router) { }

  ngOnInit(): void {
    this.recipe = this.formBuilder.group({
      title: ['', Validators.required],
      ingredients: this.formBuilder.array([
        this.formBuilder.group({
          name: ['', Validators.required],
          amount: ['', Validators.required]
        })
      ]),
      steps: this.formBuilder.array([
        this.formBuilder.control('', Validators.required)
      ])
    });
  }

  onSubmit() {
    this.recipeService.createRecipe(this.recipe.value.title, this.recipe.value.ingredients, this.recipe.value.steps).subscribe();
  }

  get steps() {
    return this.recipe.get('steps') as FormArray;
  }

  addStep() {
    this.steps.push(this.formBuilder.control('', Validators.required));
  }

  get ingredients() {
    return this.recipe.get('ingredients') as FormArray;
  }

  addIngredient() {
    this.ingredients.push(this.formBuilder.group({ name: ['', Validators.required], amount: ['', Validators.required, Validators.pattern(/^\d\s?\w+/g)] }));
    this.recipe.valid = this.recipe.valid ? !this.recipe.valid : this.recipe.valid;
  }

【问题讨论】:

  • 添加新项目后尝试拨打this.recipe.updateValueAndValidity()
  • 这行得通@Ashot!如果您输入答案,我可以接受。
  • 您可以自己添加并接受它,没问题。主要是问题解决了;-)

标签: angular angular-formbuilder


【解决方案1】:

我通过在addStepaddIngredient 函数中添加@Ashot 提到的this.recipe.updateValueAndValidity 解决了这个问题

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多