标签: angular-reactive-forms

在 formArray 中验证 formGroup 的问题

我正在创建一个带有角材料垫表的表格。

我在编写我的应用程序时使用反应式表单,表单启动看起来像这样:

myForm = this.fb.group({
    settings: this.fb.array([])
});
Run Code Online (Sandbox Code Playgroud)

我的表单是一个 formGroup,其中包含一个 formArray 控件(设置)。

设置 formArray 包含每个设置的 formGroup (mat-table 中的每一行都是一个 formGroup 并包含多个控件)。

当我尝试向其添加验证时,我的问题就开始了。

如果我只有一个带有 formControl 的 formGroup 并且其中一个是 Validators.required ,例如,表单是无效的,直到我添加了一些值,然后它才会变为有效状态。

然而,在表单数组中使用 formGroup 时,即使在向 require 字段添加一些值后,表单状态仍然无效(我什至控制台记录表单以查看内部值是否已更改)。

此外,当我尝试使用 valueChange().subscribe 捕捉更改时,仅当我从 formArray 推送/删除组时才会触发该事件,而不会在更改设置组内的现有控件时触发该事件。

如何在数组内的组中侦听内部更改事件,然后对它们使用一些自定义估值?

angular-validation angular angular-reactive-forms

2
推荐指数
2
解决办法
6578
查看次数

Angular 反应式嵌套表单

我试图在我的 angular 项目中嵌套多个反应形式,并且形式在不同的组件中。

例如,我有一个组件,其中包含一个具有两个输入的表单,一个是名称输入,一个是描述输入和一个提交按钮。我称这个组件NameDescComponent

我计划在多个页面和表单中使用这个组件。这是组件的 html。

<form [formGroup]="nameDescForm" (ngSubmit)="customEmit()">
    <div fxLayout="row" fxLayoutGap="10px" fxFlex>
      <mat-form-field>
        <input matInput placeholder="Name" formControlName="name">
      </mat-form-field>
      <mat-form-field fxFlex>
        <input matInput placeholder="Description" formControlName="description">
      </mat-form-field>
    </div>
    <div fxLayout="column" fxLayoutGap="10px">
      <button type="submit" mat-raised-button color="primary">
        {{buttonText}}
      </button>
      <div>
      </div>
    </div>
  </form>
Run Code Online (Sandbox Code Playgroud)

这是缩写的 ts 文件

public nameDescForm: FormGroup;



@Input() public buttonText: string;
  @Output() public save: EventEmitter<any> = new EventEmitter<any>();
  @Output() public nameDescFormEmit: EventEmitter<FormGroup> = new EventEmitter<FormGroup>();

  constructor(fb: FormBuilder) {
    this.nameDescForm = fb.group({
      'name': ['', Validators.required],
      'description': ['']
    });
  }

  public ngOnInit() …
Run Code Online (Sandbox Code Playgroud)

javascript typescript angular angular-reactive-forms angular-forms

2
推荐指数
1
解决办法
5891
查看次数

如何以 Angular 反应形式迭代 FormGroup 中的 FormArray

我的表格结构如下所示

-MainForm(ParentForm)
 -FormGroup(MedicineGroup)
  -FormArray(MedicineArray)
Run Code Online (Sandbox Code Playgroud)

我想对其进行迭代MedicineArray,我做了一些研究并编写了以下代码

for (let control of soForm.get('MedicineGroup').controls['MedicineArray'].controls) {
    medObj.name.push(control.controls['MedName'].value);
  }
Run Code Online (Sandbox Code Playgroud)

代码工作正常,但我收到一条警告,上面写着

Property 'controls' does not exist on type 'AbstractControl'.
Run Code Online (Sandbox Code Playgroud)

是否有其他或更好的方法来迭代 FormGroup 内的 FormArray?

javascript typescript angular angular-reactive-forms

2
推荐指数
2
解决办法
9065
查看次数

如何将角材料表单包装到组件中并将它们作为 formControl 元素公开给 FormGroup

我正在尝试将一个组件(例如称为custom-input)封装为基于 Angular 材质组件的 formControl 元素,以包含以下内容:

<mat-form-field >
  <input
    matInput
    [formControl]="inputField"
    formControlName="{{ name }}"
    name="{{ name }}"
    maxlength="{{ maxlength }}"
    placeholder="{{ name | translate }}"
    required
  />
  <mat-error *ngIf="inputField.errors">{{
    this.validationService.getErrorMsg(inputField.errors)
  }}</mat-error>
</mat-form-field>
Run Code Online (Sandbox Code Playgroud)

现在这个组件正在使用所需的功能,但不能像普通输入或 matInput一样使用 formControlName 属性绑定到 formGroup(例如下面的例子,它直接绑定到 formGroup 没有问题)

<input
  matInput
  formControlName="inputField123"
  placeholder="{{ 'testInput' | translate }}"
  required
/>
Run Code Online (Sandbox Code Playgroud)

问题是如何让上面的组合组件绑定为formGroup中的formControl元素?我应该实现或公开什么来提供此功能?

我应该使用 ControlValueAccessor 还是有更好的方法用于材质输入组件?

javascript typescript angular2-forms angular angular-reactive-forms

2
推荐指数
1
解决办法
1857
查看次数

Angular ERROR in : No provider for NgControl

我正在创建一个实现 ControlValueAccessor 的组件以在反应式表单中使用,它只是一个输入元素的包装器,上面有一些管道。

我已经注入了 NgControl 以检索有效/无效状态并将它们传播到内部输入元素。

当在另一个输入中找到输入值时,它是无效的。

这是 Stackblitz

在 Stackblitz 上工作正常,但是当我进行ng build --prod 时,它会引发错误:

错误:NgControl 没有提供程序(“[ERROR ->])

你看到任何问题吗?

谢谢!

angular angular-reactive-forms controlvalueaccessor

2
推荐指数
1
解决办法
6015
查看次数

How to create a custom form validator to accept only valid JSON in Angular

In my Angular app, I have a reactive form which for simplicity I will assume to have only one control called configJson which is represented by a <textarea> in the DOM.

I need to validate this form control to only accept valid JSON text from the user input, and display an error message otherwise.

Here's my component's class and template:

import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';

@Component({
  selector: 'app-configuration',
  templateUrl: './configuration.component.html',
  styleUrls: …
Run Code Online (Sandbox Code Playgroud)

json typescript angular-validation angular angular-reactive-forms

2
推荐指数
2
解决办法
5057
查看次数

访问表单数组值以显示 Mat 错误

表单组

this.locationForm = this.formBuilder.group({
          locationName: new FormControl(null, Validators.required),
          locationURL: new FormControl(null, Validators.required),
          workTiming: this.formBuilder.array([
            this.formBuilder.group({
              beginTime: new FormControl(null,Validators.required),
            })
          ])
        })
Run Code Online (Sandbox Code Playgroud)

HTML代码:

<div formArrayName="workTiming" >
         <div *ngFor="let item of workTiming.controls;                  
                      let pointIndex=index" [formGroupName]="pointIndex">
            <div class="container">
            <mat-form-field class="responsive">
                <input type="time" required formControlName="beginTime" matInput placeholder="Begin Time">
                <mat-error *ngIf="workTiming.get('beginTime').hasError('required')"> Enter begin time </mat-error>
            </mat-form-field>
          </div>
      </div>
    </div>
Run Code Online (Sandbox Code Playgroud)

我需要一些关于如何访问 mat-error 中“beginTime”的 formControl 名称的帮助,因为我使用的是 formArray,我不确定如何访问它。如果我在代码中给出这样的错误,我会收到如下错误

ERROR TypeError: Cannot read property 'hasError' of null
Run Code Online (Sandbox Code Playgroud)

angular angular-reactive-forms formarray

2
推荐指数
1
解决办法
3000
查看次数

实现 Angular 跨域验证的最佳方式

我试图找出在 Angular 中实现跨领域验证的最佳方法。

例如,我有一个选择字段,它使另一个字段成为必填字段。

我希望能够:

  • 如果无效,更改字段的边框颜色
  • 每当它成为必需时,在字段前显示 *
  • 显示一条特定的错误消息,说明违反了哪些验证规则。

到目前为止,我想出了三个解决方案,但它们对我来说并不那么令人信服。

  • 收听选择字段更改并更新第二个字段的验证器。
  • 监听两个字段的变化并手动执行 setErrors
  • 将验证提升到 formGroup(这可能会感觉非常麻烦,因为验证状态现在存储在 formGroup 中,而不是直接在 formControl 中可用)。

这是一个Stackblitz实现,它演示了我的调查。

reactive-forms angular angular-reactive-forms

2
推荐指数
1
解决办法
2446
查看次数

如何使用反应式表单禁用 ng-select?

如何禁用 ng-select?我尝试了 [disabled] 属性,但它在这里不起作用。还尝试使用表单控件禁用它,但没有任何效果。

Stackblitz 示例

select angular angular-reactive-forms

2
推荐指数
1
解决办法
3069
查看次数

Angular:如何访问嵌套表单中控件的值

我正在尝试在控制台和 HTML 中打印获取嵌套表单的表单控件的值。

userForm = new FormGroup({
    name: new FormControl("Tom Alter"),
    address: new FormGroup({
        Country: new FormControl("India"),
        State: new FormControl("Delhi")
    })
});
Run Code Online (Sandbox Code Playgroud)

在这两种情况下,我都可以使用 get 语句找到值。

console.log ("name : ", this.userForm.controls.name.value);
console.log ("Country using Get Way 1  : ", this.userForm.get(['address', 'Country']).value) ;
console.log ("Country using Get Way 2 : ", this.userForm.get(['address']).get(['Country']).value);
console.log ("Country using Get Way 3 : ", this.userForm.get(['address.Country']).value);
console.log ("Country without Get: ", this.userForm.group.address.controls.cCountry.value);
Run Code Online (Sandbox Code Playgroud)

在这些“名称”中,“Way1”、“Way2”正在工作,但是“Way 3”和“Without get”不起作用,因为它适用于“name”

同样在 HTML 中:

Name : {{userForm.controls.name.value}}
<br>
<br>
Country with get Way …
Run Code Online (Sandbox Code Playgroud)

angular angular-reactive-forms

2
推荐指数
1
解决办法
2481
查看次数