标签: angular-reactive-forms

使用 formGroupDirective 重置表单 - Angular 反应表单

我试图找到重置角反应形式的最佳方法。我对重置反应形式有点困惑,无法找到哪种方法适用于模板驱动形式,哪些方法是反应形式。现在我已经使用 'formGroupDirective' 来重置,但我收到如下所示的控制台错误。 在此处输入图片说明

这就是我使用 formGroupDirective 进行重置的方式。

模板文件:

<form 
  ...
  #formDirective="formGroupDirective" 
>
Run Code Online (Sandbox Code Playgroud)

TS文件:

import { ViewChild, ... } from '@angular/core';
import { FormGroupDirective, ... } from '@angular/forms';

export class MyComponent {
 ...
 @ViewChild('formGroupDirective') private formGroupDirective: FormGroupDirective;

  constructor(... )

  private someFunction(): void { 
    ...
    formGroupDirective.resetForm();
  }
}
Run Code Online (Sandbox Code Playgroud)

在这里我无法理解一件事,FormGroupDirective 和 FormDirective 之间有什么区别。以及哪一种更适合反应形式。甚至我们可以通过 formGroup 名称重置

this.formGroup.reset();
Run Code Online (Sandbox Code Playgroud)

因此,如果我们能够通过 formGroup 名称进行重置,那么为什么我们需要使用指令。如果有人有想法,请帮助我理解这些差异。

angular angular-reactive-forms

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

Angular Reactive forms 选择默认对象

我正在使用反应式表单,并且我有一个来自对象数组的选择框。我试图设置默认值,但它只是没有设置。

我的表格:

<form [formGroup]="markerForm" (ngSubmit)="onSubmit(markerForm)" novalidate>
      <div class="form-group">
        <label for="markerType">{{ 'MARKER.LABEL_TYPE' | translate }}</label>
        <select  class="form-control" formControlName="markerType"   >
           <option id="markerType" [value]="markerType.id" *ngFor="let markerType of markerTypes">{{markerType.desc}}</option>
        </select>
      </div>
</form>
Run Code Online (Sandbox Code Playgroud)

设置默认值:

const test= [{id:1, desc: 'Restaurants'}, {id:2, desc : 'Fire stations'}];
this.markerTypes= test;
console.log(this.markerTypes[1].desc);
this.markerForm.controls['markerType'].setValue( this.markerTypes[1], {onlySelf: true});
Run Code Online (Sandbox Code Playgroud)

reactive-forms angular angular-reactive-forms

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

如何显示反应式表单验证错误消息

大家好,

我正在努力为名称输入制作验证器,我只是从 angular wiki 回复了代码,但仍然无法正常工作。

你能帮我找出问题吗?

谢谢指教。

我的 HTML 代码:

  <form [formGroup]="formAlta" (ngSubmit)="addRepresentacio()">
            <div class="form-group">
              <label for="namePro">Nom</label>
              <input id="namePro" class="form-control" formControlName="namePro" placeholder="Nom del professional" required>
              <div *ngIf="namePro.invalid && (namePro.dirty || namePro.touched)" class="alert alert-danger form-danger" role="alert">

        <div *ngIf="namePro.errors.required">
            El Nom del professional es obligatori
        </div>
    </div></form>
Run Code Online (Sandbox Code Playgroud)

还有我的 TS 组件

 formAlta: FormGroup;
 ngOnInit() {
    this.formAlta = new FormGroup({
      idPro: new FormControl(),
      documentTypePro: new FormControl(),
      namePro: new FormControl('',[Validators.required]),
      rProfessional: new FormControl(this.tipusPro),
      firstSurnamePro: new FormControl(),
      secondSurnamePro: new FormControl(),
      businessNamePro: new FormControl(),
      idCli: new FormControl(), …
Run Code Online (Sandbox Code Playgroud)

typescript angular angular-reactive-forms angular5

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

有没有办法合并两个表单数组控件?

我的代码中有两个表单数组。我需要组合它们并对组合数组执行添加和删除。我需要连接每个表单数组的表单数组控件

let a = this.nextBillForm.controls["electricityBillCycleEnergyCharges"] as FormArray;
let b = this.nextBillForm.controls["electricityBillCycleOtherCharges"] as FormArray;
Run Code Online (Sandbox Code Playgroud)

1)为每个填充

a.forEach(element => {
  b.push(element);
});
Run Code Online (Sandbox Code Playgroud)

2) 串联

 a.concat(b)
Run Code Online (Sandbox Code Playgroud)

两种方式都试过了。都显示错误

angular angular-reactive-forms

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

在 Angular 8 中,如何在单击提交按钮时将所有值转换为 JSON?

我想通过单击提交按钮将带有键和值的表单数据推送为 JSON 格式。

我不想手动创建 JSON。请帮我解决这个问题。

angular-reactive-forms angular8

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

FormArray 对象上的 patchValue ?

我有一组语言供用户选择,还有一种默认语言可供选择。选择默认语言后,我想确保以编程方式选中该语言的复选框。

我不确定如何在语言的 FormArray 上使用 patchValue。

组件.ts

import { FormGroup, FormControl, FormArray, Validators } from '@angular/forms';
...

constructor(...) {
    this.languages = ['English', 'Spanish', 'Mandarin', 'Klingon'];

    this.myForm = new FormGroup({
        languages: this.createLanguagesControl(),
        defaultLanguage: new FormControl('', Validators.required)
    });
}

createLanguagesControl() {
    const controls = this.languages.map(language => {
        return new FormControl(false);
    });
    return new FormArray(controls);
}

defaultLanguageSelection() {
    let formValues = this.myForm.value;
    console.log('defaultLanguageSelection', formValues.defaultLanguage);

    let i = 0;
    for (let language of this.languages) {
        if (language == formValues.defaultLanguage) {              // find the index of …
Run Code Online (Sandbox Code Playgroud)

formbuilder angular angular-reactive-forms angular-forms formarray

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

如何扩展 Angular 表单指令以具有全局自动完成=“关闭”

正如我们在 Angular 中<form>所知道的那样,是一个指令。我想知道是否有任何方法可以扩展该指令。

我需要这个,因为我想在我的视图中autocomplete="off"使用时总是附加属性<form>。或者也许有另一种更简单的方法来全局设置它?

html typescript angular-directive angular angular-reactive-forms

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

角度复位反应形式

我正在尝试在发送表单后重置我的表单,但只有该值设置为 null。

组件.html

  <div *ngIf="!loading" fxLayout="row" class="note-textarea">
    <form  fxFlex fxLayout="column" fxLayoutGap="10px" [formGroup]="noteForm">
      <mat-form-field fxFlex>
        <textarea matInput #note rows="1" maxlength="100" placeholder="Note" formControlName="description"></textarea>
        <mat-hint align="end">{{note.value?.length || 0}}/100</mat-hint>
        <mat-error *ngIf="noteForm.get('description').errors && noteForm.get('description').touched">description is required</mat-error>
      </mat-form-field>
      <div fxFlex>
        <button mat-stroked-button class="save-btn" (click)="insertNote()">Save</button>
      </div>
    </form>
  </div>
Run Code Online (Sandbox Code Playgroud)

组件.ts

  noteForm: FormGroup = this.formBuilder.group({
    description: new FormControl(null, Validators.required)
  })
Run Code Online (Sandbox Code Playgroud)
 insertNote() {
   // bunch of code 

      this.noteForm.reset();

    }
  }
Run Code Online (Sandbox Code Playgroud)

问题是输入字段被标记为脏,如下所示:

在此处输入图片说明

reset reactive-forms angular angular-reactive-forms

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

超过 maxLength 验证时,Mat-Error 未在反应式表单中显示实际消息。角材料

我可以看到我对 textarea 表单控件的验证在超过 100 个字符时变成红色,但是,实际的 mat-error 消息没有显示出来。它适用于所需的验证。[编辑] 正确答案由下面的第一个答案解决。“maxlength”是所需的语法。

.ts

 descriptionFormGroup: FormGroup;
 descriptionCtrl = new FormControl('', [Validators.required, Validators.maxLength(100)]);

 this.descriptionFormGroup = this._formBuilder.group({
  descriptionCtrl: ['', [Validators.required, Validators.maxLength(100)]]
  });
  matcher = new MyErrorStateMatcher();
Run Code Online (Sandbox Code Playgroud)

HTML文件

<form [formGroup]="descriptionFormGroup" class="center-flex-wrapper">
        <ng-template matStepLabel>Description</ng-template>
        <mat-form-field>
            <mat-label>Description</mat-label>
            <textarea matInput formControlName="descriptionCtrl" placeholder="Your Description" required [errorStateMatcher]="matcher"></textarea>
            <mat-hint>Max length is 100 characters</mat-hint>
            <mat-error *ngIf="descriptionFormGroup.controls.descriptionCtrl.hasError('maxLength')">Max length exceeded</mat-error>
            <mat-error *ngIf="descriptionFormGroup.controls.descriptionCtrl.hasError('required')">Description is required</mat-error>
        </mat-form-field>
    </form>   
Run Code Online (Sandbox Code Playgroud)

错误状态匹配器

export class MyErrorStateMatcher implements ErrorStateMatcher {
isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
const isSubmitted …
Run Code Online (Sandbox Code Playgroud)

angular-material angular angular-reactive-forms

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

Angular Form 精确 10 个字母数字字母模式验证

我对反应式表单字段验证的这个特定用例有以下问题。

目前我只设置了这个规则:

this.projectForm = this.fb.group({
  .....................................................................................,
  .....................................................................................,
  .....................................................................................,
  CIG: [null, [Validators.required, Validators.minLength(10),Validators.maxLength(10)]],
Run Code Online (Sandbox Code Playgroud)

目前我正在检查插入到我的CIG表单字段中的值是否正好有 10 个字符作为长度。

我的问题是我还必须检查这是一个字母数字字符串(由 10 个字符组成)。

所以这样的事情是允许的:ABCED12345但不允许这样的事情:ABCD-12345

如何使用Validators实现这种行为?我需要使用 REGEX 或类似的东西吗?

angular-validation angular angular-reactive-forms

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