gpt4 book ai didi

angular - 如何在 Angular 中单击按钮时将 FormControl 动态添加到 FormArray?

转载 作者:行者123 更新时间:2023-12-03 18:32:16 26 4
gpt4 key购买 nike

如何添加 formcontrol(option)动态在 formarray ?我想动态添加问题到 formarray .单击按钮后,它应该更新显示。我正在使用 Angular 7。
组件代码

ngOnInit() {
this.quizForm = this.fb.group({
questions: this.fb.array([]),
questions2: this.fb.array([]),
});
}

//creating formcontrol
createItem(): FormGroup {
return this.fb.group({
ques: '',
});
}

//pushing code
genField() {
this.message = true;
this.questions = this.quizForm.get('questions') as FormArray;
this.questions.push(this.createItem());
}
HTML模板
我想在按钮单击时动态添加表单控件选项,表单控件应该在 formArrayName="questions" 内.
<form [formGroup]="quizForm" class="adjust-form">
<div formArrayName="questions"
*ngFor="let item of quizForm.get('questions').controls; let i = index;">
<div class="col-md-10 col-sm-6 mt-3 mb-3" [formGroupName]="i">
<label>{{i +1}} - {{question}} </label>
<i class="flaticon-delete"
(click)="quizForm.get('questions').controls.splice(i,1) "
style="font-size: 9px;padding-left: 80px;">
</i>
<div class="row">
<input type="text" class="form-control col-10"
[(ngModel)]="item.ques" formControlName="ques"
placeholder="Enter your question" required>
<button *ngIf="i == 0" (click)="genField()" type="button"
class="btn btn-secondary btn-elevate btn-circle btn-icon ml-4">
<i class="flaticon2-plus"></i>
</button>
</div>
<div *ngIf="item.touched && item.invalid" class="kt-font-danger text-left">
<p>required</p>
</div>
</div>
</div>
</form>

最佳答案

此示例动态地将电子邮件字段添加到响应式(Reactive)表单。这将用于使用户能够添加多个电子邮件地址(例如家庭和工作)。
此演示具有以下依赖项:Angular 8、Angular Material , Bootstrap 4
最终结果 ( Stackblitz Demo )
Angular Form Demo - dynamically add form controls
步骤 1:定义表单模型

constructor(private formBuilder: FormBuilder) { }

ngOnInit() {
this.emailForm = this.formBuilder.group({
emails: this.formBuilder.array([this.createEmailFormGroup()])
});
}
第二步:定义一个动态构造new的方法 FormGroup
private createEmailFormGroup(): FormGroup {
return new FormGroup({
'emailAddress': new FormControl('', Validators.email),
'emailLabel': new FormControl('')
})
}
第三步:定义动态添加新的方法 FormGroupFormArray
public addEmailFormGroup() {
const emails = this.emailForm.get('emails') as FormArray
emails.push(this.createEmailFormGroup())
}
第 4 步(可选):定义删除方法 FormGroup
public removeOrClearEmail(i: number) {
const emails = this.emailForm.get('emails') as FormArray
if (emails.length > 1) {
emails.removeAt(i)
} else {
emails.reset()
}
}
步骤 5:创建 HTML 表单模板
<form [formGroup]="emailForm">
<div formArrayName="emails">
<div class="row" *ngFor="let email of emailForm.get('emails').controls; let i = index"
[formGroupName]="i">
请注意,在 formArrayName 内element,动态邮箱 FormGroups根据数组索引命名。
最终形式
<mat-toolbar color="primary">
Angular Form Demo - Dynamically add form controls
</mat-toolbar>

<form class="basic-container" [formGroup]="emailForm">
<div formArrayName="emails">
<div class="row" *ngFor="let email of emailForm.get('emails').controls; let i = index"
[formGroupName]="i">

<div class="col-1">
<mat-icon class="mt-3">email</mat-icon>
</div>

<mat-form-field class="col-4">
<input matInput formControlName="emailAddress" placeholder="Email" autocomplete="email">
<mat-error *ngFor="let validation of validationMsgs.emailAddress">
<div *ngIf="email.get('emailAddress').hasError(validation.type)">
{{validation.message}}
</div>
</mat-error>
</mat-form-field>

<mat-form-field class="col-4">
<mat-label>Label</mat-label>
<mat-select formControlName="emailLabel">
<mat-option *ngFor="let label of emailLabels" [value]="label">
{{label}}
</mat-option>
</mat-select>
</mat-form-field>

<div class="col-3">
<button class="float-left" mat-icon-button color="primary" aria-label="Remove/clear"
(click)="removeOrClearEmail(i)" matTooltip="Remove">
<mat-icon>highlight_off</mat-icon>
</button>
<button class="float-left" mat-icon-button color="primary" aria-label="Add"
(click)="addEmailFormGroup()" matTooltip="Add">
<mat-icon>add_circle_outline</mat-icon>
</button>
</div>
</div>
</div>
</form>
最终组件
import {Component} from '@angular/core';
import {FormBuilder, FormArray, FormControl, FormGroup, Validators} from '@angular/forms';

@Component({
selector: 'form-app',
templateUrl: 'app.component.html'
})
export class AppComponent {
public emailForm: FormGroup;
public emailLabels = ['Home', 'Work', 'Other'];
public validationMsgs = {
'emailAddress': [{ type: 'email', message: 'Enter a valid email' }]
}

constructor(private formBuilder: FormBuilder) { }

ngOnInit() {
this.emailForm = this.formBuilder.group({
emails: this.formBuilder.array([this.createEmailFormGroup()])
});
}

public addEmailFormGroup() {
const emails = this.emailForm.get('emails') as FormArray
emails.push(this.createEmailFormGroup())
}

public removeOrClearEmail(i: number) {
const emails = this.emailForm.get('emails') as FormArray
if (emails.length > 1) {
emails.removeAt(i)
} else {
emails.reset()
}
}

private createEmailFormGroup(): FormGroup {
return new FormGroup({
'emailAddress': new FormControl('', Validators.email),
'emailLabel': new FormControl('')
})
}
}

关于angular - 如何在 Angular 中单击按钮时将 FormControl 动态添加到 FormArray?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59033703/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com