gpt4 book ai didi

Angular/Reactive Forms - 添加或删除 FormControl 列表 - 绑定(bind)模板(带演示)

转载 作者:行者123 更新时间:2023-12-02 09:09:11 25 4
gpt4 key购买 nike

我有一个 matSelect 因为我可以选择 1 到 10 之间的数字,具体取决于我必须使用 *ngFor 显示相同数量的 matInput 的数字。 select 中默认选择的数字是 1(因此默认情况下我们也有一个 matInput)

<mat-form-field>
<mat-select placeholder="Number of winners to reward" [value]="selected" (selectionChange)="selectNumber($event)">
<mat-option *ngFor="let emailNumber of totalEmailsNumber" [value]="emailNumber">
{{ emailNumber }}
</mat-option>
</mat-select>
</mat-form-field>

<div formArrayName="mails">
<mat-form-field *ngFor="let email of form.get('mails').controls; let i = index">
<textarea matInput [formControlName]="i"></textarea>
</mat-form-field>
</div>

添加第一个MatInput的默认FormControl,我这样做:

this.form.controls['mails'] = this.fb.array(this.emailsNumber.map(() => new FormControl('', Validators.required)));

这可行,但我无法管理添加另一个 FormControl 或删除它的逻辑,例如,如果用户在选择中选择 10 然后将其更改为 4,并管理模板中的绑定(bind)。

我还想知道 *ngFor="let email of form.get('mails').controls 是一个好的做法吗?


Here's a Minimal StackBlitz Demo to work with

最佳答案

尝试一下:

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

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

constructor(private fb: FormBuilder) {
}

ngOnInit() {
this.totalEmailsNumber = this.createCustomLengthArray(10);
this.form = this.fb.group({
mails: this.fb.array([])
});
}

get mails() {
return (<FormArray>this.form.controls['mails']);
}

selectNumber(emailNumbers) {
const difference = this.mails.length - emailNumbers;
difference > 0 ? this.removeMails(difference) : this.addMails(difference);
}

removeMails(difference) {
this.createCustomLengthArray(difference)
.forEach(item => this.mails.removeAt(this.mails.length - 1));
}

addMails(difference) {
this.createCustomLengthArray(difference)
.forEach(
item => {
this.mails.push(this.fb.control(null, Validators.required));
}
);
}

createCustomLengthArray(length) {
return (new Array(Math.abs(length)))
.fill(null)
.map((item, index) => index + 1);
}
}

在模板中:

<form [formGroup]="form">
<mat-form-field>
<mat-select
placeholder="Number of winners to reward"
[value]="selected"
(selectionChange)="selectNumber($event.value)">
<mat-option
*ngFor="let emailNumber of totalEmailsNumber"
[value]="emailNumber">
{{ emailNumber }}
</mat-option>
</mat-select>
</mat-form-field>

<div formArrayName="mails">
<mat-form-field
*ngFor="let email of form.controls['mails'].controls; let i = index">
<textarea
matInput
[formControlName]="i">
</textarea>
</mat-form-field>
</div>
</form>

Here's a Working Sample StackBlitz for your ref.

关于Angular/Reactive Forms - 添加或删除 FormControl 列表 - 绑定(bind)模板(带演示),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54616922/

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