标签: angular-reactive-forms

如何从表单组中禁用的表单控件中获取值作为 Stream ?(如 valueChanges 方法)

Angular 在表单组内禁用 FormControl 的常规行为是省略控制器的键/值。但我需要保留表单对象结果的结构 - 所以我需要禁用控制器的键出现在最终表单值对象内。

有一个简单的解决方案可以使用方法“getRowValue()”获取它,但它不是流......有一种内置的方法可以将它获取到流中吗?

例子

myForm = new FormGroup({   
    name:new FormControl({value:'',disabled:true}),
    power:new FormControl('')
  })
Run Code Online (Sandbox Code Playgroud)

valueChanges() {power:anyValue} 的结果

我需要{power:anyValue,name:""}

stackblitz 中的示例

angular angular-reactive-forms

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

Angular Material:使用反应形式选择多个默认值以进行对象选择

我正在使用反应形式和角度材料垫选择来创建一个形式,并启用多重选择。我有一个要在垫选择中加载的对象列表,并且希望默认情况下预先选择该列表中的某些项目。

默认选择与字符串(下面的示例中的苏打水)配合良好,并且默认项目显示为选中图标,垫选择元素值已加载它们,如果我添加更多项目,它们将添加到值字段中的现有项目中。

但我想要在垫选择中加载的项目是对象(下面示例中的 energyDrinks),当我设置垫选择字段的值时,即使字段值设置正确,默认情况下也不会检查它们。另外,如果我添加一个项目,值字段中的现有数据将被新项目覆盖。

有什么方法可以让预选项目在 UI 选择框中选中,并让新添加的项目添加 mat-select 元素的现有值?

提前致谢

下面是示例代码 -

html-

<form [formGroup]="drinkCategory">

<mat-form-field class="full-width">
    <mat-select multiple formControlName="sodaName">
        <mat-option *ngFor="let soda of sodaList" [value]="soda">
            {{soda}}
        </mat-option>
    </mat-select>
</mat-form-field>

<p>{{drinkCategory.get('sodaName').value | json}}</p>


<mat-form-field class="full-width">
    <mat-select multiple formControlName="energyDrinkName">
        <mat-option *ngFor="let energyDrink of energyDrinksList" [value]="energyDrink">
            {{energyDrink.name}}
        </mat-option>
    </mat-select>
</mat-form-field>

<p>{{drinkCategory.get('energyDrinkName').value | json}}</p>
</form>

Run Code Online (Sandbox Code Playgroud)

.ts 文件 -

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

@Component({
  selector: 'drink-example',
  styleUrls: ['drink-example.css'],
  templateUrl: 'drink-example.html',
})
export class DrinkExample …
Run Code Online (Sandbox Code Playgroud)

angular angular-reactive-forms mat-form-field

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

如何使用 angular8 将动态对象数组分配给 formgroup

您好,我从 API 命中获取对象数组,该对象数组必须分配给 formGroup。我尝试过使用 formGroup 绑定,但它检测到真/假值,但它不会给我对象数组中更改的真/假值,而是只给我真/假,而且我在另一个数组中也有日期输入字段,它也不会检测真/假值或更改的值。如果我写的代码是错误的,那么请纠正我并帮助我以有效的方式编写。

帮助表示赞赏。

演示:演示

TS:

 private settingsInfoForm() {
    if (!this.agentDetailsList) {
      // Add
      this.agentSettingsInfoForm = this.FB.group({
        agentToogles: this.FB.array(this.detailsToggle.map(x=> x.boolValue)),
        restrictionsInfo:this.FB.array(this.Restrictions.map(x=>x.boolValue))
      });
    } else {
      // Edit
      if (this.agentDetailsList) {
       this.detailsToggle = this.agentDetailsList
       this.agentSettingsInfoForm = this.FB.group({
          agentToogles: this.FB.array(this.detailsToggle.map(x=>x.boolValue)),
           restrictionsInfo:this.FB.array(this.Restrictions.map(x=>x.boolValue))
      })
      }
      this.agentSettingsInfoForm.valueChanges.subscribe(data => {
          this.formEdit = true;
          console.log('agentSettingsInfoForm', this.formEdit)
        })
      }
    }
Run Code Online (Sandbox Code Playgroud)

HTML:

<form [formGroup]= "agentSettingsInfoForm">
<div class="row row-cols-2" formGroupName="agentToogles">
              <div class="col" *ngFor="let toggleValue of detailsToggle;let i = index">
                <div class="custom-control custom-switch mb-3">
                    <input type="checkbox" [formControlName]="i" …
Run Code Online (Sandbox Code Playgroud)

angular angular-reactive-forms formarray

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

从 formArray 中删除 FormControl

我创建了我的 FormGroup 如下

this.GSTNForm = this.formbuilder.group({
      gstRegistrationStatusId: new FormControl(''),
      reasonForNonApplicabilityofGST: new FormControl(''),
      isExemptGoods: new FormControl(false),
      goodServiceRemarks: new FormControl(''),
      gstandbankDetails: this.formbuilder.array([
        this.formbuilder.group({
          _id: new FormControl(''),
          sequenceNo: new FormControl(this.gstnSequenceValue),
          gstn: new FormControl(''),
          addressline1: new FormControl(''),
          addressLine2: new FormControl(''),
          stateCode: new FormControl(''),
          cityCode: new FormControl(''),
          countryCode: new FormControl(''),
          pinCode: new FormControl(''),
          accountHolderName: new FormControl(''),
          accountTypeId: new FormControl(''),
          bankName: new FormControl(''),
          branchName: new FormControl(''),
          bankCountryCode: new FormControl(''),
          accountNo: new FormControl(''),
          ifscCode: new FormControl(''),
          micrCode: new FormControl(''),
          swiftCode: new FormControl('')
        })
      ])
    });
Run Code Online (Sandbox Code Playgroud)

我有些想删除_id …

typescript angular angular-reactive-forms

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

单击关闭按钮时如何停止激活角度反应表单验证

我在模式弹出窗口中有一个反应式表单,但是当我第一次打开模式时,必填字段具有焦点。当我单击关闭按钮时,会触发验证(我认为是通过失去焦点),并显示所需的字段验证消息,但按钮不会单击即。按钮后面的代码不运行。如果你再次点击它,一切都会正常。

这些是 TS 文件的相关位:

  ngOnInit() {
    this.addPaymentForm = this.formBuilder.group({
      jobId: ['', [Validators.required, Validators.maxLength(9)]],
      grossAmount:  ['', [Validators.required, Validators.max(10000), Validators.min(-10000)]]
    });
  }

  get f() { return this.addPaymentForm.controls; }

  close() {
    this.activeModal.close({ dataModified: false });
  }
Run Code Online (Sandbox Code Playgroud)

这是 HTML:

<form [formGroup]="addPaymentForm" (ngSubmit)="submit()">
    <label for="jobId">Job Id</label>
    <input type="number" id="jobId" class="form-control" formControlName="jobId" required>
    <div *ngIf="f.jobId.invalid && (f.jobId.dirty || f.jobId.touched)" class="alert alert-danger mt-2">
        <div *ngIf="f.jobId.errors.required">
            Job Id is required
        </div>
        <div *ngIf="f.jobId.errors.maxlength">
            Invalid Job Id
        </div>
    </div>

    <label for="grossAmount">Gross Amount</label>
    <input id="grossAmount" type="number" class="form-control" formControlName="grossAmount" required>
    <div …
Run Code Online (Sandbox Code Playgroud)

angular angular-reactive-forms

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

Angular Form 控件在组件初始化时无效,无需执行任何操作

在组件初始化时,所有带有验证器的表单控件都被标记为无效,而不采取任何操作。

component.html

<form [formGroup]="form" (ngSubmit)="submit()">
  <input type="text" formControlName="phone" [class.error]="form.get('phone').invalid">
  <button type="submit">goo</button>
</form>
Run Code Online (Sandbox Code Playgroud)

component.ts

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

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  form: FormGroup;

  constructor(public fb: FormBuilder) {
      this.form = this.fb.group({
          phone: [
              null,
              [Validators.required, Validators.minLength(9), Validators.maxLength(9), Validators.pattern('^[0-9]*$')]
          ]
      });

      console.log(this.form);
  }

  submit() {
      if (this.form.invalid) return;

      console.log(this.form.value);
  }
}

Run Code Online (Sandbox Code Playgroud)

斯塔克闪电战

angular angular-reactive-forms

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

修补表单时,控件的更改检测如何工作?

我想知道以下情况会发生什么:

我有一个带有这些控件的 formGroup:

{
  forename: new FormControl()
  surname: new FormControl()
}
Run Code Online (Sandbox Code Playgroud)

现在我像这样跟踪控件“姓氏”的变化(只是一个例子):

this.formGroup.get('surname').valueChanges.subscribe(changes => {
   if(this.formGroup.get('forename') == 'Max'){
      this.formGroup.get('forename').disable();
   }
})
Run Code Online (Sandbox Code Playgroud)

最后我像这样修补我的表单:

this.formGroup.patchForm({surname: 'Muster', forename: 'Max'});

控件“名字”会被禁用吗?因为我不确定它是否会在设置控件“名字”的值之前触发控件“姓氏”的更改。因此,“名字”可能还没有“正确”值。

我试图更好地理解,当触发确切的 valueChanges 事件时,因为我有时会遇到问题,但值没有设置,尽管它们应该设置。

我还想知道是否可以等到每个控件都修补完毕然后发出更改。

angular angular-reactive-forms angular-changedetection

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

如何将 [formControlName] 与 mat-checkbox 一起使用

在 Angular Material 文档中,他们说[formControlName]不能与mat-checkbox. 如何根据值数组动态创建复选框并使用反应式表单获取复选框值?还有其他方法吗?

typescript form-control angular-material angular angular-reactive-forms

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

如何在 Angular 10 中修补动态表单数组的值?

我有一个动态 formArray,保存数据,一切工作正常,但我在修补值时遇到问题,而且我在网上找不到任何确切的解决方案。

下面是代码,

    <form [formGroup]="educationAndExperienceForm">
        <div formArrayName="educationForm">
            <div *ngFor="let education of educationAndExperienceForm.controls.educationForm['controls'];let i = index;"
                [formGroupName]="i">
                <h6 class="text-left circularBold" *ngIf="i == 0"><b>Highest Qualification</b></h6>
                <input type="text" class="education-inputs w-100 mt-3" placeholder="School/College/University"
                    formControlName="school"
                    [ngClass]="{ 'input-error': submitted && educationAndExperienceForm.controls.educationForm.controls[i].invalid }">
                <input type="text" class="education-inputs w-100 mt-3" placeholder="Degree Ex: Master's"
                    formControlName="degree"
                    [ngClass]="{ 'input-error': submitted && educationAndExperienceForm.controls.educationForm.controls[i].invalid }">
                <input type="text" class="education-inputs w-100 mt-3"
                    placeholder="Field of Education Ex: Computer Science" formControlName="specialization"
                    [ngClass]="{ 'input-error': submitted && educationAndExperienceForm.controls.educationForm.controls[i].invalid }">
                <div class="text-left">
                    <input type="text" class="education-inputs w-100 mt-3" placeholder="Graduate Year"
                        formControlName="passed_year"
                        [ngClass]="{ …
Run Code Online (Sandbox Code Playgroud)

javascript typescript angular angular-reactive-forms angular10

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

Angular Material 将初始焦点设置为表单控件,无需单击事件

我正在使用 Angular 9 和 Material。我有一个步进器,它将引导用户完成我们的工作流程的步骤。

我需要用户能够完全使用键盘完成这些步骤,而无需单击控件。我见过很多通过单击事件将焦点设置在控件上的示例。我不希望用户必须单击按钮才能将焦点设置在第一个文本区域。 当步进器初始化时,如何才能获得文本区域的初始焦点,而无需用户单击任何内容? 我尝试在 ngAfterViewInit 中使用元素引用,但它不起作用。谁能帮助我理解如何做到这一点?谢谢。

这是我的 HTML:

<pseudo-common-tool-header title="{{this.title}}"></pseudo-common-tool-header>
<div class="pseudo-content-manager-tool-area">
<mat-horizontal-stepper #stepper>
<mat-step [stepControl]="formGroup">
    <form [formGroup]="formGroup">
        <ng-template matStepLabel>Workstation Ids</ng-template>
        <div>
            <mat-form-field appearance="outline" class="eris-width-45" >
            <mat-label>List of Old/New Workstations to swap (one pair per line)</mat-label>
            <textarea #wkstns rows="8" #workstations matInput placeholder="Old Workstation, New Workstation" formControlName="workstations" required></textarea>
            </mat-form-field>
        </div>
        <div>
            <mat-form-field appearance="outline" >
                <mat-label>Soft Delete Date</mat-label>
                <input matInput #softDate [min]="minDate" [matDatepicker]="picker3" formControlName="removalDate">
                        <mat-datepicker-toggle matSuffix [for]="picker3"></mat-datepicker-toggle>
                        <mat-datepicker #picker3 color="primary"></mat-datepicker>
            </mat-form-field>
        </div>
        <div>
            <button color="primary" #step1next mat-raised-button matStepperNext>Next</button> …
Run Code Online (Sandbox Code Playgroud)

typescript angular-material angular angular-reactive-forms

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