标签: angular-reactive-forms

Angular:在更改另一个表单控件时触发表单控件验证

请在此处参考 stackblitz 中的项目 。

可以看出,我的反应形式的控件为firstNumber、secondNumber和thirdNumber。我需要对表单控件进行验证thirdNumber,使其值不应大于在firstNumber和之间具有最小值的表单控件的值secondNumber。

validateThirdNumber每当表单控件发生更改时,组件中的自定义验证器都可以正常工作thirdNumber,但我需要对表单控件的更改进行验证firstNumber,secondNumber因为验证逻辑也可以根据表单控件的更改 firstNumber而更改secondNumber。

为此,我添加了一个有关表单控件更改的事件firstNumber,并将secondNumber表单控件标记thirdNumber为touched但其验证似乎没有被触发。

那么,如何在表单控件thirdNumber发生变化时触发表单控件firstNumber的验证secondNumber?

另外,为什么this.myFormGroup有时在自定义验证器中未定义(请参阅登录于app.componen.ts)line:22,即使在绑定this到其表单控件声明并this.myFormGroup在 中定义后也是如此 constructor ?

angular angular-reactive-forms angular-custom-validators

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

对 FormGroup 进行更改后,如何在单元测试中触发 valueChanged 可观察对象?

我正在一个包含反应式表单 (FormGroup) 和 valueChanges 订阅的组件上编写单元测试代码,但我还没有弄清楚如何确保 FormGroup 发出 valueChanges 事件。

// In the component under test:
this.formGroup.get('field').valueChanges
     .subscribe((obj: any[]) => {
         debugger; // BREAKPOINT
         dataObject.fieldValues = [ ... ];
         ... details here should be unimportant ...
     });

// In the unit test:
it('should set dataObject from field component', fakeAsync(() => {
        [
    values: string[] = [ ... ];

    component.formGroup.get('field').setValue(values);
    component.formGroup.get('field').updateValueAndValidity({ emitEvent: true });
    fixture.detectChanges();
    tick();

    expect(component.dataObject.fieldValues.length).toEqual(values.length);

}));

Run Code Online (Sandbox Code Playgroud)

我无法让单元测试规范命中组件订阅代码中的断点。

unit-testing angular angular-reactive-forms

5
推荐指数
1
解决办法
7975
查看次数

触发 Angular 异步 FormGroup 验证

背景

仅当该组及其所有子项的所有同步验证均有效时,才会执行 FormGroup 上的异步验证。

问题

我想在所有子项都有效之前在 FormGroup 上执行 asyncValidator。

this.myForm = new FormGroup({
  country: [ null, [ Validators.required ] ],
  postalCode: [ null ],
  unrelatedField1: [ null ],
  unrelatedField2: [ Validators.min(123) ]
}, {
  validators: [ postalCodeFormat ],
  asyncValidators: [ postalCodeExists ]
})
Run Code Online (Sandbox Code Playgroud)

我的自定义 postalCodeExists 验证器需要国家/地区和邮政编码字段。它不关心“unrelatedField2”的有效性。

有什么方法可以手动触发 FormGroup 的异步验证吗?

我的第一个想法

据我所知这是不可能的。

this.myForm.valueChanges.pipe(
  map(...etc),
  distinctUntilChanges(...etc)
).subscribe(() => {
  if (this.myForm.get('country').valid && this.myForm.get('postalCode').valid) {
    this.myForm.executeAsyncValidationPlease();
  }
});
Run Code Online (Sandbox Code Playgroud)

我的第二个想法

this.myForm = new FormGroup({
  countryAndPostalCodeGroup: new FormGroup({
    country: [ null, [ Validators.required ] ], …
Run Code Online (Sandbox Code Playgroud)

angular angular-reactive-forms

5
推荐指数
0
解决办法
1164
查看次数

角度反应形式验证嵌套字段

我正在使用Angular 7

我有一个嵌套的反应形式

this.salonProfileForm = this.fb.group({
  salonName: new FormControl('', [Validators.required]),
  address: this.fb.group({
    city: new FormControl('', [Validators.required])
  })
});

get f() {
    return this.salonProfileForm.controls;
}
Run Code Online (Sandbox Code Playgroud)

我有这样的 HTML 表单

<input type="text" formControlName="salonName" required />
<ng-container *ngIf="submitted && f.salonName.invalid && (f.salonName.dirty || f.salonName.touched)">
   <small *ngIf="f.salonName.errors.required">
      Salon name is required
   </small>
</ng-container>

<div formGroupName="address">
  <input type="text" formControlName="city" />
  <ng-container *ngIf="submitted && f.city.invalid && (f.city.dirty || f.city.touched)">
    <small *ngIf="f.city.errors.required">
        city is required
    </small>
  </ng-container>
</div>
Run Code Online (Sandbox Code Playgroud)

但这会在城市输入ng-container字段上产生错误,如下所示

ERROR TypeError: Cannot read property 'invalid' …
Run Code Online (Sandbox Code Playgroud)

angular angular-reactive-forms

5
推荐指数
1
解决办法
6041
查看次数

patchValue 设置值并禁用该字段

我正在推送带有一些值的 FormArray,并且在加载列表后我需要在某些字段中动态设置禁用属性。我的问题是:有没有办法仅使用 patchValue 设置值并设置禁用属性?

我尝试过类似 this.rowArray.controls[index].patchvalue({format: "NUMBER",disabled:true}) 但它似乎不起作用。

  this.rowList.forEach((el, index) => {
              this.rowArray.push(
                this.fb.group(
                  {
                    name: new FormControl(el.name, [
                      Validators.required,
                      Validators.maxLength(30),
                      Validators.pattern(this.BAN_SPECIAL_BUT_UNDERSCORE)
                    ]),
                    source: new FormControl(el.source, Validators.required)
.....
Run Code Online (Sandbox Code Playgroud)

在那之后

    if (this.rowArray.controls[index].get("source").value === "CSV") {
                this.rowArray.controls[index].patchValue({
                  format: "NUMBER",
                  disabled: true
                });
              }
Run Code Online (Sandbox Code Playgroud)

rowList 是我来自后端的矩阵。

angular angular-reactive-forms

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

为什么 Angular ReactiveForms FormArray 会抛出错误“TypeError:无法读取 null 的属性‘updateOn’”

大家好,我有一个具有一组角色的 Formarray。在编辑期间,它会动态删除并在该表单数组中添加角色,直到这里一切正常,但是当我提交表单时,它会引发错误并且页面会刷新。

错误:TypeError:无法读取 null 的属性“updateOn”

我还附上了下面的屏幕截图在此处输入图片说明

form-control angular-reactive-forms formarray angular6

5
推荐指数
1
解决办法
1717
查看次数

存在哪些方法可以区分以编程方式修改的表单控件与由用户修改的表单控件?

我使用角度反应表单来创建带有文本字段的表单。

如果字段的数据已存储,我会预先填充字段。现在我可以允许用户导航到这些表单来编辑字段。

我想在编辑文本字段时调用一个函数,这可能会清除其下面的其他字段。

但我不希望该函数在以编程方式修改文本字段(在本例中为预填充)时清除要调用的其他字段。

如何使用 Angular React Forms 及其 API 来实现这一目标?表单控件上的标志类似于用户操作和编程预填充,pristine或者touched受用户操作和编程预填充的影响。

angular angular-reactive-forms

5
推荐指数
1
解决办法
280
查看次数

ngIf 角反应形式分量值

我有一组单选按钮。如果用户选择值“是”,我想在表单上显示一个附加框。

https://stackblitz.com/edit/angular-4bgahw?file=src/app/personal/personal.component.ts

HTML.component

<div formGroupName="radioButtonsGroup" class="form-group col-6 pl-0 pt-3">

    <div class="form-check-inline" *ngFor="let item of personal.radioButtonsdata">
        <label for="{{item.section}}" class="col-12 customradio"
            ><span>{{item.section}}</span>
            <input [value]="item" id="{{item.section}}" type="radio" formControlName="selectedButton"/>
            <span class="checkmark"></span>
        </label>
    </div>

    <!-- <div class="col-md-8" *ngIf="selectedButton.control.item === 'yes'"> --> //my attempt to target above input value
  <div class="col-md-8" >
        <input type="text" formControlName="title" class="form-control" placeholder="Title">
</div>
    </div>
Run Code Online (Sandbox Code Playgroud)

任何人都可以让它工作并告诉我我在这里做错了什么吗?

javascript typescript angular angular-reactive-forms

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

Angular 在父组件嵌套表单中使用子组件表单

将子组件表单放入父组件表单的最佳方法是什么?我们使用的是 2019 年最新的 Angular 8。经过研究,以下方法不能完全奏效。

父组件:

 ngOnInit() {
    this.parentForm = this.fb.group({
       childForm1: etc
    })
Run Code Online (Sandbox Code Playgroud)

子组件:

this.ChildForm = this.formBuilder.group({
  'streetNumber': [null, [Validators.required, Validators.maxLength(32)]],
  'streetType': [null, [Validators.maxLength(8)]],
  'city': [null, [Validators.maxLength(32)]],
  'state': [null, [Validators.maxLength(16)]],
  'postalCode': [null, [Validators.maxLength(16)]],
}, { validator: atLeastOneLocationRequired })
Run Code Online (Sandbox Code Playgroud)

}

方法一:

这个方法,https: //itnext.io/partial-reactive-form-with-angular-components-443ca06d8419 经过严格测试表明 ParentForm 有效,即使 Child Form 无效。这不应该发生。

ngOnInit() {
  this.parent = this.fb.group({
    fullName: null
  })
Run Code Online (Sandbox Code Playgroud)

}

formInitialized(name: string, form: FormGroup) {
  this.checkoutForm.setControl(name, form);
}
Run Code Online (Sandbox Code Playgroud)

方法二:

方法 2 使用 ViewChild,这是听力不好的做法。 https://davembush.github.io/attaching-an-angular-child-component-s-form-to-a-parent/

@ViewChild(ChildComponent) childComponent: ChildComponent;

And now in ngAfterViewInit() …
Run Code Online (Sandbox Code Playgroud)

typescript angular angular-reactive-forms angular8

5
推荐指数
1
解决办法
7925
查看次数

Angular 反应形式 - 在模糊时验证但在键入时更新模型

我有一个使用反应形式和输入文本的情况。

我需要:

  1. 当用户输入时,根据输入的内容建议一个列表(我使用的是 ngx bootstrap typeahead);
  2. 仅当用户失去输入焦点时才验证输入字段。

为了仅在用户离开输入字段时执行输入验证,我在验证选项中添加了“updateOn: 'blur'”。问题是这不仅会影响执行验证的时间,还会影响模型的更新时间。使用“模糊”,模型仅在用户离开输入文本时更新,因此建议列表无法按用户类型正常工作,因为模型没有更新。

我在stackblitz 中添加了一个示例。

我想知道是否有一种方法可以只对模糊执行验证,但模型会随着用户键入而更新。

谢谢。

angular angular-reactive-forms

5
推荐指数
1
解决办法
1846
查看次数