标签: angular-reactive-forms

_this.form.get不是angular4中的函数

我开发一个角度4应用程序,并在将数据绑定到表单时遇到问题.绑定代码似乎很好,不知道问题是什么.当我调试应用程序时,我可以看到结果正确填充了下面的代码行this.editMovieForm = result; 在setFormValues()方法中.当我检查控制台窗口时,我看到以下错误

EditmovieComponent.html:1 ERROR TypeError: _this.form.get is not a function
    at forms.es5.js:4907
    at Array.forEach (<anonymous>)
    at FormGroupDirective.webpackJsonp.../../../forms/@angular/forms.es5.js.FormGroupDirective._updateDomValue (forms.es5.js:4906)
    at FormGroupDirective.webpackJsonp.../../../forms/@angular/forms.es5.js.FormGroupDirective.ngOnChanges (forms.es5.js:4774)
    at checkAndUpdateDirectiveInline (core.es5.js:10840)
    at checkAndUpdateNodeInline (core.es5.js:12341)
    at checkAndUpdateNode (core.es5.js:12284)
    at debugCheckAndUpdateNode (core.es5.js:13141)
    at debugCheckDirectivesFn (core.es5.js:13082)
    at Object.eval [as updateDirectives] (EditmovieComponent.html:1)


ERROR Error: Uncaught (in promise): TypeError: _this.editMovieForm.patchValue is not a function
TypeError: _this.editMovieForm.patchValue is not a function
    at main.bundle.js:446
    at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invoke (polyfills.bundle.js:2908)
    at Object.onInvoke (vendor.bundle.js:146628)
    at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invoke (polyfills.bundle.js:2907)
    at Zone.webpackJsonp.../../../../zone.js/dist/zone.js.Zone.run (polyfills.bundle.js:2658)
    at polyfills.bundle.js:3389
    at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invokeTask (polyfills.bundle.js:2941)
    at …
Run Code Online (Sandbox Code Playgroud)

angular angular-reactive-forms angular4-forms

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

Angular 5 + Angular Material Select + Reactive Forms ==不显示初始选项

正如标题所说,我有一个包含多个<mat-select>内容的反应形式.在初始表单加载时,即使form.value显示初始选项,也不会显示初始选项.

相关组件:

export class DesJobInfoEditComponent implements OnInit {

...

currentJobData: IJob;
jobTypes: IJobType[];

...

constructor(private fb: FormBuilder) {

    ...

        // Construct forms
        this.createForm();

        this.initializeForm();

}

createForm() {
    this.editJobInfoForm = this.fb.group({
        ...
        JobType: '', // mat-select
        ...
    });
}

initializeForm() {
    this.rebuildForm();
}

rebuildForm() {
    this.editJobInfoForm.reset({
        ...
        JobType: this.jobTypes[this.currentJobData.JobType].DisplayDesc,
        ...
    });
}
Run Code Online (Sandbox Code Playgroud)

}

相关的HTML:

<mat-form-field fxFlex>
      <mat-label>Job Type</mat-label>
       <mat-select formControlName="JobType" placeholder="Job Type">
              <mat-option *ngFor="let jobType of jobTypes" value="jobType.value">
                     {{ jobType.DisplayDesc }}
               </mat-option>
        </mat-select>
  </mat-form-field>
Run Code Online (Sandbox Code Playgroud)

加载表单时,选择不显示最初选择的选项,但是,它们设置正确,显然:

Form value …
Run Code Online (Sandbox Code Playgroud)

angular-material angular angular-reactive-forms

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

角度反应形式设置和清除验证器

请协助,我想删除表格中的所有验证人,请告知是否可能,如果您有表格组20或更多表单控件,如果不是更好的方法删除验证器,请参阅下面的示例.

 ngOnInit() {
    this.exampleFormGroup = this.formBuilder.group({
     surname: ['', [Validators.required, Validators.pattern('^[\\w\\s/-/(/)]{3,50}$')]],
     initials: ['', [Validators.required, Validators.maxLength(4)]]
     });
  }

 public removeValidators() {
    this.exampleFormGroup.get('surname').clearValidators();
    this.exampleFormGroup.get('initials').clearValidators();
    this.exampleFormGroup.updateValueAndValidity();
 }

 public addValidators() { 
  this.exampleFormGroup .get('surname').setValidators([Validators.required,Validators.pattern('^[\\w\\s/-/(/)]{3,50}$')]);
  this.exampleFormGroup.get('initials').setValidators([Validators.required, Validators.maxLength(4)]);
  this.exampleFormGroup.updateValueAndValidity(); 
 }
Run Code Online (Sandbox Code Playgroud)

上面的方法addValidators()将添加验证器,并removeValidators()在执行时删除验证器.但我遇到的问题是,我必须指定表单控件我试图清除验证器.有没有办法this.exampleFormGroup.clearValidators();在表单中完成并清除所有内容并再次this.exampleFormGroup.setValidators()将其设置回来.我知道我可能会要求一个独角兽,但在formGroup有20个或更多控件的情况下,清除和设置验证器可能会很痛苦,因此非常感谢如何处理这些场景的地图.

angular angular-reactive-forms

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

ANGULAR 6:错误TS2315:类型'ModuleWithProviders'不是通用的

您好我遇到了一个与任何事情无关的问题.

我展示了一些我的代码,希望它可以有用.

考虑到一旦我开始创建一个Reactive Form就出现了这个问题.

首先,这是我的package.json:

{
  "name": "name",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^6.0.3",
    "@angular/common": "^6.0.3",
    "@angular/compiler": "^6.0.3",
    "@angular/core": "^6.0.3",
    "@angular/forms": "^6.1.2",
    "@angular/http": "^6.0.3",
    "@angular/platform-browser": "^6.0.3",
    "@angular/platform-browser-dynamic": "^6.0.3",
    "@angular/router": "^6.0.3",
    "@ng-bootstrap/ng-bootstrap": "^2.2.0",
    "core-js": "^2.5.4",
    "rxjs": "^6.0.0",
    "zone.js": "^0.8.26"
  },
  "devDependencies": {
    "@angular/compiler-cli": "^6.0.3",
    "@angular-devkit/build-angular": "~0.6.8",
    "typescript": "~2.7.2",
    "@angular/cli": "~6.0.8",
    "@angular/language-service": "^6.0.3",
    "@types/jasmine": "~2.8.6",
    "@types/jasminewd2": "~2.0.3",
    "@types/node": "~8.9.4",
    "codelyzer": …
Run Code Online (Sandbox Code Playgroud)

typescript angular angular-reactive-forms

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

如何在 Angular 中将 patchValue 与 FormArray 一起使用?

我有一个 FormGroup ,其中有一个这样的元素。

books: this.fb.array([this.buildBookFormGroup()])
Run Code Online (Sandbox Code Playgroud)

fb 是 FormBuilder。buildBookFormGroup() 函数返回一个 FromGroup,以便我可以从同一表单添加/删除多本书。

buildBookFormGroup(): FormGroup {
    return this.fb.group({
      author: new FormControl(''),
      price: new FormControl(0),
    });
  }
Run Code Online (Sandbox Code Playgroud)

我有获取表单控件、在“书籍”控件中添加和删除表单组的功能。

现在,我已经使用这种形式添加了多本书并保存它们。我想创建一个编辑页面,在其中获取现有数据并填充表单。为此,我使用“patchValue”。但是,patchValue 不适用于 FormArray。看了很多问题和答案,我更加困惑了。这是我修补的方式。

if (this.bookshop.books.length > 0) {
      let booksFormGroupArray: FormGroup[] = [];
      this.bookshop.books.forEach((book, index) => {
        booksFormGroupArray.push(this.buildBookFormGroup());
        Object.keys(booksFormGroupArray[index].controls).forEach(key => {
          booksFormGroupArray[index].patchValue({
            [key]: book[key]
          })
        })
      });
      this.bookForm.patchValue({
        books: this.fb.array(booksFormGroupArray)
      });
    }
Run Code Online (Sandbox Code Playgroud)

只有第一本书对象被插入到表单的“书籍”中。有什么解决方法吗?

angular angular-reactive-forms

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

类型“AbstractControl | null' 不可分配给类型'FormGroup'

我[formGroup]在 Angular 中传递给子组件时遇到问题。它说Type 'AbstractControl | null' is not assignable to type 'FormGroup'。我想我已经设置了所有安全条件并且我已经很好地初始化了它。我不明白为什么这种情况仍然发生。错误是在[formGroup]="linkAccounts?.get('bank')"这个link-accounts.component.html

注册.组件.ts

linkAccountsForm = this.formBuilder.group({
  bank: this.formBuilder.group({
    bank_name: [null, Validators.required],
    account_name: [null, Validators.required],
    account_number: [null, Validators.required],
    swift_code: [null, Validators.required],
  }),
  credit_card: this.formBuilder.group({
    name: [null, Validators.required],
    card_number: [null, Validators.required],
    cvc: [null, Validators.required],
    exp_date: [null, Validators.required],
  }),
});
Run Code Online (Sandbox Code Playgroud)

注册.component.html

<form
  [formGroup]="linkAccountsForm"
  (ngSubmit)="onLinkAccount(linkAccountsForm)"
>
  <app-link-accounts
    [linkAccounts]="linkAccountsForm"
    [step]="step"
    [submitted]="submitted"
  ></app-link-accounts>
</form>
Run Code Online (Sandbox Code Playgroud)

链接账户.component.ts

 @Input() linkAccounts!: FormGroup;
 @Input() step!: number;
 @Input() submitted!: boolean;
Run Code Online (Sandbox Code Playgroud)

链接-accounts.component.html

<div [formGroup]="linkAccounts" *ngIf="step === …
Run Code Online (Sandbox Code Playgroud)

typescript angular angular-reactive-forms angular-forms

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

为什么 FormArray 不能分配给 NgIterable&lt;any&gt;?

我尝试将 FormArray 传递到组件中。该组件模板迭代 FormArray 并显示数据。它允许用户添加到数组或删除项目。

子组件 ts

@Input()
public formArray!:FormArray;
Run Code Online (Sandbox Code Playgroud)

然后在模板中我尝试:

<div class="formRow child2" *ngFor="let year of formArray; let i=index">
  List Number #{{i+1}} &nbsp; &nbsp;
  <mat-form-field class="col3 no-bottom" appearance="fill">
    <mat-label>{{ "YEAR" | translate }}</mat-label>
    <input matInput placeholder="Year" mask="0000" [formControl]="year">
  </mat-form-field>
    <button mat-flat-button color="accent" (click)="addYear()">
      <span class="material-icons">Add Year</button>
Run Code Online (Sandbox Code Playgroud)

但是,我收到一条错误消息:

Type 'FormArray' is not assignable to type 'NgIterable<any> | null | undefined'.
<div class="formRow child2" *ngFor="let year of formArray; let i=index">
Run Code Online (Sandbox Code Playgroud)

谁能解释为什么会发生这种情况?高度赞赏。

angular-material angular angular-reactive-forms

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

角度反应形式,动态验证器不更新控制有效性

所以我有一个表单,其中仅当另一个控件有值时才需要一个控件,为此我创建了以下结构

 profileGroup = this.fb.group({
username: [''],
address: [
  '',
  [
    (control: AbstractControl) => {
      if (this.profileGroup?.get('username')?.value) {
        return (Validators.required)(control);
      }
      return (Validators.nullValidator)(control);
    },
  ],
],
Run Code Online (Sandbox Code Playgroud)

});

这个函数效果很好,一旦username 控件获得一个值,aValidators.required就会添加到address控件中。但是,尽管添加了验证器,但控件的有效性address并未更新,因此控件仍标记为valid。

如果可能的话我想避免使用类似的东西

this.profileGroup.get('username')?.valueChanges.subscribe(val=>{
  this.profileGroup.get('address')?.updateValueAndValidity()
})
Run Code Online (Sandbox Code Playgroud)

因为可能存在我不知道名称的动态控件,并且不想为每个控件设置一个可观察对象。

这是一个工作示例的堆栈闪电战 https://stackblitz.com/edit/angular-10-formbuilder-example-m8qjq8?file=src/app/app.component.ts

formbuilder angular-validation angular angular-reactive-forms angular-validator

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

Angular 14 中的类型化表单显示“&lt;any&gt;”而不是类型

在使用最新版本的 Angular(版本 14)时,我似乎没有做得很好,因此严格类型化的反应式表单无法按预期工作。

表单是ngOnInit使用injected在内部初始化的FormBuilder。

 public form!: FormGroup;

 constructor(private formBuilder: FormBuilder) {}

 ngOnInit(): void {
    this.initializeForm();
  }

  private initializeForm(): void {
    this.form = this.formBuilder.group({
      title: ['', [Validators.required, Validators.minLength(3)]],
      content: ['', Validators.required],
    });
  }
Run Code Online (Sandbox Code Playgroud)

现在,当我尝试访问表单的控件时,没有自动完成功能,类型为FormGroup<any>。此外,当尝试访问对象上不存在的控件时,它不会引发错误FormGroup。

  • 例子:

在此输入图像描述

  • package.json

在此输入图像描述

  • 角度官方文档:

https://angular.io/guide/typed-forms

forms typescript angular angular-reactive-forms angular14

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

表单重置后角度保留输入值

我有一个包含两个字段的反应式表单。第一个是使用 ControlValueAccessor 的自定义输入,最后一个只是常规的 HTML 输入。

问题是,执行 form.reset() 后,自定义输入的值将被保留,即使其反应形式的值已经为 null。

在此输入图像描述

正如您在图像中看到的,我第一次输入并清除值时,它运行良好。

但是,第二次及以后,输入值仍然保留在自定义输入组件中。同时,无论我单击“清除输入”多少次,正常的 HTML 输入都会被清除并且运行良好。你能帮我吗?我错过放东西了吗?

文件:

  • app.component.ts/html:表单所在的位置
  • custom-input.component.ts/html:自定义输入组件

表格如下:

.ts 文件

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

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

  constructor(private fb: FormBuilder) {
    this.form = this.fb.group({
      firstName: [{ value: '', disabled: false }],
      lastName: [{ value: '', disabled: false }],
    });
  }

  clearInput() {
    this.form.reset();
  }
}
Run Code Online (Sandbox Code Playgroud)

html 文件:

<form [formGroup]="form">
  <app-custom-input formControlName="firstName"></app-custom-input>
  <input formControlName="lastName" …
Run Code Online (Sandbox Code Playgroud)

typescript angular angular-reactive-forms

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