标签: formgroups

角度| 如何在初始化FormGroup之后扩展它?

我正在Angular6中编写一个系统.系统使用表格,用FormGroup.实现.

问题:如何在初始化后扩展表单?

例:

ngOnInit() {
    this.form = new FormGroup({
          'field_1': new FormControl(null),
          'field_2': new FormControl(null)});

    if (a == 'some value') {
       // Extend this.form with field_2 and field_3
    }
}
Run Code Online (Sandbox Code Playgroud)

forms angular formgroups

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

使用 FormArray Angular 在 formGroup 中加载数据

我有一个带有 FromGroup 和 FormArray 的动态表单。动态表单运行良好,我可以添加新元素等。另一方面,我在表单中默认加载对象列表时遇到问题。例如,如果我有一个包含两个对象的列表,我希望有两个包含其两个对象数据的表单......我在这里有一个关于 stackblitz 的例子: 在此处输入图片说明https://stackblitz.com/edit/angular-4crhvw

PS:在我的示例 stakblitz 中,我制作了显示元素的示例,但我想显示所有元素

将我想发布的内容作为附件查看

form-control angular formarray formgroups

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

Angular7:NullInjectorError:没有 FormGroup 的提供者

我真的很沮丧,因为我不知道发生了什么。今天早上一切正常,就在我进行了一些更改以将 ReactiveForm 中的 2 个表单合并在一起之前,现在我在浏览器中收到以下错误:

错误:StaticInjectorError(AppModule)[FormGroup]:
StaticInjectorError(Platform:core)[FormGroup]:NullInjectorError:没有提供程序组!错误:StaticInjectorError(AppModule)[FormGroup]:
StaticInjectorError(Platform:core)[FormGroup]:NullInjectorError:没有提供程序组!

我正在导入FormsModuleReactiveFormsModule在我的app.module.ts文件中:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
[...]
@NgModule({
  declarations: [
    AppComponent,
    CustomersComponent,
    HeaderComponent,
    CustomersListComponent,
    CustomerEditComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    FormsModule,
    ReactiveFormsModule,
    ...
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
Run Code Online (Sandbox Code Playgroud)

然后是我组件中的 FormGroup:

import { FormGroup, FormControl, Validators } from '@angular/forms';
[...]
Run Code Online (Sandbox Code Playgroud)

然后在组件中声明一个新的 FormGroup 。我尝试@angular/forms使用 npm重新安装该软件包,但仍然出现错误...我看过一些类似的问题,但据我所知,这与测试环境有关。如果您有任何想法,请提前致谢。

forms angular formgroups

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

Angular Material-在FormArray的扩展面板上使用* ngFor后,应用程序崩溃

首先,感谢@ AJT_82提供的建议!

我一直在研究一个更简单的代码重现错误的示例,可以在stackblitz.com/edit/angular-42gobh中 找到该错误。注释了有问题的行,以便您可以检查出正确的结果。只需取消注释, <div [formGroup]="i"></div> 就可以使一切崩溃

基本上,我有一个为组件构建表单的服务,并且HTML文件使用Angular Material。当手风琴用于formArray时,应用程序完全崩溃,并且无法正确分配formGroup:

customer-edit.service.ts:

import { Injectable } from '@angular/core';
import { FormGroup, FormBuilder, FormArray, Validators } from '@angular/forms';

@Injectable({
  providedIn: 'root'
})
export class CustomerEditService {
  private cusForm: FormGroup = this.fb.group({
    thirdParty: this.fb.group({
      name: this.fb.control(null),
      vat: this.fb.control(null),
      corpoPhone: this.fb.control(null),
      corpoMail: this.fb.control(null),
      corpoWeb: this.fb.control(null),
      activityNumber: this.fb.control(null),
      addresses: this.fb.array([]),
      contacts: this.fb.array([])
    }),
    docRefs: this.fb.group({}),
    commentsArr: this.fb.group({})
  });

  constructor(
    private fb: FormBuilder
    ) {    }

    // **** EMPTY FORMS GETTERS …
Run Code Online (Sandbox Code Playgroud)

angular-material ngfor angular formarray formgroups

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

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

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

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

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 Reactive Form

我目前正在与 Angular 表单数组作斗争。

我有一个表单,可以在其中动态添加字段。

我已经创建了表单对象:

this.otherDataForm = this.fb.group({
});
Run Code Online (Sandbox Code Playgroud)

我添加这样的动态字段:

addField(field: CustomFormField): void {
    this.otherDataForm.addControl(id_campo, new FormControl('', Validators.required));
}
Run Code Online (Sandbox Code Playgroud)

我遍历这些字段:

<form *ngIf="selectedProfile" [formGroup]="otherDataForm">
      <div class="mb-3" *ngFor="let field of fields; let i = index">
           <label>{{field.descripcion}}</label>
           <input class="form-control" [formControlName]="field.id_campo" type="number">
      </div>
</form>
Run Code Online (Sandbox Code Playgroud)

但是,如果需要该字段,我似乎无法控制每个字段的错误以显示验证消息。

任何人都可以帮我解决这个问题吗?也许有更好的方法来做到这一点。

javascript forms angular formarray formgroups

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

如何在 Angular 15 中通过条件禁用反应表单中的输入 FormControl?

我有一个可以输入学生 ID 的表格。下面是两个输入框,全名和电子邮件。当我加载页面时,仅应启用学生 ID 输入框,并禁用其下方的两个输入。当我输入学生 ID 并且它有记录时,这是唯一一次启用全名和电子邮件的输入框。

当我使用 Angular 13 时,它能够对每个输入进行处理

[attr.disable]="!isStudentIdReal"
Run Code Online (Sandbox Code Playgroud)

然而,我最近更新到 Angular 15,它就停止工作了。我能够找到一个解决方案:

studentName : [{value: '', disable: true}],
email : [{value: '', disable: true}]
Run Code Online (Sandbox Code Playgroud)

这会禁用输入框,但是不会启用它们,因为我没有条件。

form-control angular formgroups angular15

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

如何在 Angular 中正确使用 FormArray 类型

我应该如何声明这个类型?

假设我有一个FormGroup

  1. 我在构造函数中实例化它。
export interface MyType {
 myValue: string
}
Run Code Online (Sandbox Code Playgroud)
myForm: FormGroup
myArray: FormArray // <FormControl<MyType>>

constructor(private _formBuilder: FormBuilder) {
  myForm = new FormGroup({
    myArray: this._formBuilder.array([])
  })
}
Run Code Online (Sandbox Code Playgroud)
  1. 因为我在某个地方有一个按钮可以让我向数组添加新元素,所以我执行以下操作
addElement() {
  this.myArray = this.myForm.get('myArray') as unknown as FormArray

  this.myArray.push(this.newElement())
}

private _newElement(): FormGroup { // What type to use ? 
  return this._formBuilder.group({
     myValue: ''
  })
}
Run Code Online (Sandbox Code Playgroud)

但是当我使用

myArray: FormArray<FormControl<MyType>>
Run Code Online (Sandbox Code Playgroud)

我收到以下错误

Argument of type 'FormGroup<any>' is not assignable to parameter of type 'FormControl<MyType>'.
  Type 'FormGroup<any>' is missing the following properties …
Run Code Online (Sandbox Code Playgroud)

types typescript angular formarray formgroups

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

类型“AbstractControl”上不存在 Angular 5 嵌套表单和验证以及属性“控件”

我已经设置了一个嵌套的表单组。到目前为止一切正常。但是当有嵌套的表单元素时,我不确定如何正确设置验证警报。

发生的一件特别的事情是在构建期间我收到错误:“AbstractControl”类型上不存在属性“控件”

这是我的代码:

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

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
  name = 'Reactive Form - Nested FormGroups';

  myForm: FormGroup;

  constructor(
    private fb: FormBuilder
  ) {}

  ngOnInit() {
    this.buildForm();
  }

  buildForm() {

    this.myForm = this.fb.group({

      user : this.fb.group({
        'firstName': new FormControl('', Validators.required),
        'lastName': new FormControl('', Validators.required)
      }),

      'bio': new FormControl()
    });
  }
}
Run Code Online (Sandbox Code Playgroud)

我的问题是验证看到带有 class="validation-message" 的 …

typescript angular formgroups

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

Angular 5表单组列表控件或对其进行迭代

我在formgorup中使用angular 5,并希望对控件进行迭代,以便基于表单创建动态组件,表单字段由外部数据服务(数据库等)提供

声明如下

check = new FormGroup({
    firstName : new FormControl(true),
    lastName : new FormControl(false)
  });
Run Code Online (Sandbox Code Playgroud)

我发现说明了如何迭代控件,但是它不起作用。我尝试使用:

for(let item of this.check.controls){}
Run Code Online (Sandbox Code Playgroud)

并得到这是chrome调试:

无法读取未定义的属性“长度”

我无法访问this.check.controls.keys或keys()

我该如何迭代密钥?

谢谢

forms web angular-fullstack angular formgroups

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

Angular - 删除我在表单组中添加的最后一个数组

在我的NgOnInit()上,我\xc2\xb4m 创建一个像这样的新表单。

\n\n
  ngOnInit(){\n    this.expenseForm = this.fb.group({\n      type: \'\',\n      expenses: this.fb.array([this.buildExpense()])\n    })\n  }\n
Run Code Online (Sandbox Code Playgroud)\n\n

我有一个名为type的,它在我的对象上以空开头,还有一个名为expenses的键

\n\n

每次用户单击按钮时,这些费用键都会收到一个数组。

\n\n
  buildExpense(): FormGroup {\n    return this.fb.group({\n      description: \'\',\n      quantity: \'\',\n      price: \'\'\n    })\n  }\n\n  addExpense(): void {\n    this.expenses.push(this.buildExpense())\n  }\n
Run Code Online (Sandbox Code Playgroud)\n\n

网页

\n\n
  <button class="btn btn-outline-primary add" type="button" (click)="addExpense()">Add Expense</button>\n
Run Code Online (Sandbox Code Playgroud)\n\n

我的目标是删除表单组中添加的最后一个数组

\n

arrays angular angular-reactive-forms formgroups

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

如果 FormControl 有“.”,为什么 FormGroup.Get() 返回 null 在名字里?

问题: 我创建了一个formGroupusing formbuilder. FormGroup 有一个控件,其.名称中有。现在,当我尝试formControl使用formGroup.get方法时,它返回null

代码

export class AppComponent implements OnInit  {
  name = 'Angular';
  obj = {};
  formGroup: FormGroup;

  constructor(private formBuilder: FormBuilder) {

  }

  ngOnInit() {
    this.obj["parent.child"] = new FormControl();
    this.obj["parent"] = new FormControl();

    this.formGroup = this.formBuilder.group(this.obj);

    // All controls
    console.log(this.formGroup.controls);

    // This is the problem its not geting the form control if I have '.' in the name of form control.
    console.log(this.formGroup.get("parent.child"));

    // If I am getting …
Run Code Online (Sandbox Code Playgroud)

angular angular-reactive-forms formgroups

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

当标记为必需的控件为空时,为什么我的 Angular FormGroup 有效?

我正在尝试为选择设置基本表单验证。

在我的构造函数中我有以下内容FormGroup

this.formSubmission = new FormGroup(
  {
    triggers: new FormControl(['', [ Validators.required]])
  }
)
Run Code Online (Sandbox Code Playgroud)

我在屏幕上有一个按钮来测试其有效性FormGroup,即使没有选择“触发器”,它也总是返回有效。

单击后,将执行以下代码:

console.log('FormGroup Status: ' + this.formSubmission.status)
Run Code Online (Sandbox Code Playgroud)

这将返回 VALID。

其 HTML 部分可以在这里找到:

<div [formGroup]="formSubmission">
  <mat-form-field appearance="fill">
    <mat-label>Triggers</mat-label>
    <mat-select 
    formControlName="triggers" multiple
    >
      <mat-option *ngFor="let trigger of triggersList" [value]="trigger.TRIGGER_NAME">{{trigger.TRIGGER_NAME}}</mat-option>
    </mat-select>
  </mat-form-field>
</div>
Run Code Online (Sandbox Code Playgroud)

javascript forms typescript angular formgroups

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