标签: angular-reactive-forms

无法设置要在反应形式中选择的值

我的组件中有一个反应式表单。当组件初始化时,我想将值设置为组件中的选择字段,而不是作为选项。订阅该值后,可以从服务器获取可观察到的值,我想在其中显示该值选择字段作为默认值

我试过

this.formName.get('controlName').setValue('valueFromServer')
Run Code Online (Sandbox Code Playgroud)

this.formName.get('controlName').patchValue('valueFromServer')
Run Code Online (Sandbox Code Playgroud)

还有几个 stackoverflow 解决方案,但这些对我不起作用。这是我的 stackblitz 示例。有人可以告诉我这里出了什么问题吗

https://stackblitz.com/edit/angular-izarqy

angular angular-reactive-forms

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

TypeError:将循环结构转换为 JSON 属性“名称”会关闭循环

我在 Angular 8 中使用反应式表单将数据插入数据库,但收到此错误TypeError: Converting circular structure to JSON。据说name财产是一个循环结构,我无法找出原因。谁能帮我吗?提前致谢。

我的组件.ts

export class AddMainCategoryComponent implements OnInit {
    nm;
    desc;
    date;

    get name() {
        return this.addMCform.get('name')
    }

    get description() {
        return this.addMCform.get('description')
    }
    constructor(public mainCategoryService: MainCategoryService, private fb: FormBuilder) { }

    addMCform = this.fb.group({
        name: ['', [Validators.required, Validators.minLength(3)]],
        description: ['']
    })

    ngOnInit() {
    }

    addMain_categories() {
        let main_category = {
            nm: this.name,
            desc: this.description,
            date: new Date(),

        }
        this.mainCategoryService.addMain_categories(main_category).then(data => {
            console.log(data);
        })
    }
}
Run Code Online (Sandbox Code Playgroud)

html

<div class="container-fluid"> …
Run Code Online (Sandbox Code Playgroud)

angular angular-reactive-forms

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

对于不相关的模型字段,角度反应形式抛出“无法找到带有名称的控件”

我正在尝试使用 Angular Reactive 表单构建一个编辑组件。但是,我收到错误“错误:找不到名称为:已创建的表单控件。”,其中“已创建”是我的模型上的属性。

但是,created 不是可编辑字段,不应绑定到表单。我没有在我的表单生成器中指定它,我的 edit.html 页面上也没有控件。它仅出现在我的模型上。如何告诉表单验证器忽略此属性和其他不相关的模型属性?

这是我的模型:

        export class User {
      id: number;
      userName: string;
      password: string;
      passwordHash: string;
      lastName: string;
      firstName: string;
      email: string;
      created: string;
      lastLogin: string;
      description: string;
      isSaved: boolean;
      passsword:string;
      passwordConfirm:string;
    }
Run Code Online (Sandbox Code Playgroud)

这是我的组件:

    import { Component, OnInit, Inject } from '@angular/core';
import { Router } from "@angular/router";
import { FormBuilder, FormGroup, Validators } from "@angular/forms";
import { first } from "rxjs/operators";
import { User } from "../../model/user.model";
import { UserService } from "../../service/user.service";


@Component({ …
Run Code Online (Sandbox Code Playgroud)

javascript typescript form-control angular angular-reactive-forms

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

如何模拟 FormBuilder 以进行 Angular 组件单元测试

我正在从事 Angular 9 项目。

我有一个组件接受 formBuilder 作为来自父组件的输入。这是我的子组件(我正在测试的组件):

export class ChildComponent implements OnInit {
  @Input() parentForm: FormGroup;  //this is coming from the parentComponent

  ngOnInit(): void {
    if (this.parentForm) {
      this.filteredSelectables = this.parentForm
        .get("recipientTypes")
        ...
    }
  }
...
Run Code Online (Sandbox Code Playgroud)

我想为此组件编写测试,但我需要创建一个测试可以使用的表单(或者我需要模拟父组件并返回我想要的表单?)

我已将 FormBuilder 添加到 testBed 提供程序中,但我仍然不知道如何制作可以测试的模拟表单。“应该创建”测试正在通过,但我无法测试其他任何内容,因为它们的parentForm 不能为空。这是我当前的测试:

describe("ChildComponent", () => {
  let component: ChildComponent;
  let fixture: ComponentFixture<ChildComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ChildComponent, MatAutocomplete],
      providers: [FormBuilder],
      schemas: [CUSTOM_ELEMENTS_SCHEMA]
    })
      .compileComponents()
      .then(() => {
        fixture = TestBed.createComponent(ChildComponent);
        component = fixture.componentInstance;
      });
  }));

  beforeEach(() => { …
Run Code Online (Sandbox Code Playgroud)

testing formbuilder angular angular-reactive-forms angular9

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

在 mat-table 的 table 标签中使用 multiTemplateDataRows 和 formArrayName 时出现错误

我一直在尝试将 multiTemplateDataRows 与反应式表单一起使用,并在 mat-table 的表标签中给出 formArrayName ,但出现错误Cannot find control with path: 'bankRelationData ->

但是当我从表标记中删除multiTemplateDataRows指令时,这工作正常,请找到下面的代码

表.组件.html

<form [formGroup]="bankRelationForm">
<table mat-table [dataSource]="dataSource" multiTemplateDataRows formArrayName="bankRelationData" class="mat-elevation-z8">
  <ng-container matColumnDef="position">
        <th mat-header-cell *matHeaderCellDef> No. </th>
        <td mat-cell *matCellDef="let element"> {{element.position}} </td>
    </ng-container>

  <ng-container matColumnDef="name">
        <th mat-header-cell *matHeaderCellDef> Name </th>
        <td mat-cell *matCellDef="let element"> 
      <div>
      {{element.name}} 
      </div>
      </td>
    </ng-container>

  <ng-container matColumnDef="weight">
        <th mat-header-cell *matHeaderCellDef> Weight </th>
        <td mat-cell *matCellDef="let element"> {{element.weight}} </td>
    </ng-container>

  <ng-container matColumnDef="symbol">
        <th mat-header-cell *matHeaderCellDef> Symbol </th>
        <td mat-cell …
Run Code Online (Sandbox Code Playgroud)

frontend angular-material angular angular-reactive-forms material-table

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

为什么 uniqueUntilChanged 不能在 Angular 的 asyncValidators 中工作

当我出于某种原因按下表单输入上的按键时,异步验证器不会检测到distinctUntilChanged,并且它仍然发送API请求。例如,如果我按 35,删除 5,然后再次添加 5,它仍然会发送请求。这是代码:(我已经尝试了几乎所有方法,但仍然不起作用)

validateSomeNumber(control: FormControl): Observable<any> | Promise <any> {
    this.isSubmitBtnDisabled = true;
    return control.valueChanges.pipe(
      debounceTime(1000),
      distinctUntilChanged(),
      switchMap((value) => {
        return this.apiService.someApiRequest({ 'to_number': control.value }).pipe(
          map(res => {
            console.log(res);
            if (res.success) {
              // console.log(res);
              this.isSubmitBtnDisabled = false;
              return null;
            } else {
              // console.log(res);
              this.isSubmitBtnDisabled = true;
              return{ 'invalidCharacters': true };
            }
          }),
        );
      }),
      first()
    );
  }
Run Code Online (Sandbox Code Playgroud)

validation asynchronous operators rxjs angular-reactive-forms

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

反应式表单中的角度表单组与表单控件和表单生成器

我是角度新手。我发现该代码具有三种变体。我想知道这三者在响应式表单(表单组、表单生成器和表单控件)中实现有什么区别。

是否存在基于一种方法的应用程序性能相对于另一种方法的优先级,或者这只是偏好?

addressFormControl = new FormControl(undefined, [
  Validators.required,
  Validators.address,
]);

export class BusinessComponent {
  BusinessForm = new FormGroup({
    email: this.emailFormControl,
    firstName: new FormControl(''),
    lastName: new FormControl(''),
    address: new FormGroup({
      street: new FormControl(''),
      city: new FormControl(''),
      state: new FormControl(''),
      zip: new FormControl('')
    })
  });
}

export class BusinessComponent {
  constructor(private fb: FormBuilder) { }
  businessForm = this.fb.group({
    business: this.businessFormControl,
    firstName: [''],
    lastName: [''],
    address: this.fb.group({
      street: [''],
      city: [''],
      state: [''],
      zip: ['']
    }),
  });
}
Run Code Online (Sandbox Code Playgroud)

typescript form-control angular angular-reactive-forms formgroups

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

Angular FormArray setValue 与来自服务的数据

我在 FormArray 方面遇到问题,可能需要一些帮助。\n我有一个带有变量 FormArray 的表单,它可以工作,我可以将数据发送到后端。\n问题是,我无法设置从我收到的数据中的值后端。

\n

这是打字稿代码

\n
this.form = this.fb.group({\n  title: new FormControl("",[Validators.required]),\n  actors: new FormArray([])\n})\n\nthis.moviesService.getMovie(this.movieId).subscribe(movieData => {\n  this.movie = movieData;\n  this.form.patchValue({\n    title: this.movie.title,\n    actors: this.movie.actors,           \n  })\n})\n
Run Code Online (Sandbox Code Playgroud)\n

然后在 html 中单击按钮,我调用此函数

\n
addActor(){\n  const actorsForm = this.fb.group({\n    actor: \'\',\n    role: \'\'\n  })\n  this.actors.push(actorsForm);\n}\n\nremoveActor(i: number){\n  this.actors.removeAt(i);\n}\n
Run Code Online (Sandbox Code Playgroud)\n

和 HTML:

\n
<form [formGroup]="form" (submit)="onSubmit()">\n  <table  formArrayName="actors">\n    <tr>\n      <th colspan="2">Besetzung:</th>\n      <th width="150px">\n        <button type="button" mat-stroked-button color="primary" (click)="addActor()">Hinzuf\xc3\xbcgen +</button>\n      </th>\n    </tr>\n    <tr *ngFor="let actor of form.get(\'actors\')[\'controls\']; let i=index" [formGroupName]="i">\n      <td>\n …
Run Code Online (Sandbox Code Playgroud)

typescript angular angular-reactive-forms formarray

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

如何使用 Angular 12 材料验证密码并确认密码?

我希望得到你的很多帮助。我无法在版本 12 中使用 Angular 材料验证密码字段并确认密码。我在 html 中使用下面的结构。

<div>
  <mat-form-field>
    <mat-label>Password</mat-label>
    <input matInput 
           type="password" 
           placeholder="Digite sua senha" 
           [type]="hide ? 'password' : 'text'"
           [formControl]="passwordFormControl" />
    <mat-icon matSuffix (click)="hide = !hide">
           {{ hide ? 'visibility' : 'visibility_off' }}
    </mat-icon>
    <mat-error>               
    </mat-error>
  </mat-form-field>
</div>
<div>
  <mat-form-field>
    <mat-label>Confirm Password</mat-label>
    <input matInput
           type="password" 
           placeholder="Digite novamente sua senha"
           [type]="hide ? 'password' : 'text'" 
           [formControl]="passwordFormControl"/>
    <mat-icon matSuffix (click)="hide = !hide">
      {{ hide ? 'visibility' : 'visibility_off' }}
    </mat-icon>
    <mat-error>               
    </mat-error>
  </mat-form-field>
</div>
Run Code Online (Sandbox Code Playgroud)

forms angular-material angular angular-reactive-forms

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

监听 Angular 反应形式中的表单有效状态变化

我有一个相当复杂的页面,其中有许多嵌套组件,其中一些组件上有带有输入的表单(大部分是反应式的,尽管我确信某处有一些模板驱动的表单)。页脚中有一个“提交”按钮,只有在所有表单上的所有输入都有效的情况下才应该启用该按钮。

我决定创建一个“页面有效性服务”,它将保存所有无效表单的列表,并公开一个“有效”可观察值供按钮使用。这意味着每当表单的有效性发生变化时,每个组件都必须调用“将我添加到无效表单列表”或“从无效表单列表中删除我”。为了最大限度地减少调用次数,我只想在表单状态真正发生变化(即从有效变为无效,反之亦然)时进行调用,我尝试订阅 statusChanges:

this.formGroup.statusChanges.subscribe((status) => {}
Run Code Online (Sandbox Code Playgroud)

但每次更新值时都会触发该值(我已将其设置为 onBlur),无论状态是否已更改。事实上,它似乎与 onChanges 完全同时触发。有没有办法仅在有效性实际发生变化时收到表单通知,或者我是否必须在每个组件中手动进行检查?该项目采用 Angular 13。

angular angular-reactive-forms

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