gpt4 book ai didi

javascript - 如何在 Angular 4 的 FormArray 中禁用 FormControl

转载 作者:搜寻专家 更新时间:2023-10-30 21:15:46 25 4
gpt4 key购买 nike

我写了下面的代码片段,我认为它会禁用 FormArray 中的 FormControl

some.component.html

<form [formGroup]="testForm">
<div *ngFor="let num of countArr">
<input type="text" formNameArray="arrs">
</div>
</form>

some.component.ts

countArr = [1, 2, 3, 4, 5];
count = 5;
arrs;
testForm: FormGroup;

this.testForm = this.formBuilder.group(
arrs: this.formBuilder.array([])
);

this.arrs = this.testForm.get('arrs');

for (let i = 0; i < this.count; i++) {
this.arrs.insert(i, new FormControl({value: '', disabled: true}));
}

但是在for执行完成后,我检查了表单,发现没有任何东西被禁用。你能告诉我我哪里做错了吗??? :-)

谢谢你的帮助!!! :-)

最佳答案

首先,您的 html 组件应该是这样的:

<form [formGroup]="testForm">
<div formArrayName="arrs">
<div class="form-group" *ngFor="let arrItem of testForm.get('arrs').controls; let i = index">
<input type="text" class="form-control" [formControlName]="i">
</div>
</div>
</form>

您不需要在 html 组件中重复一些随机的 count 变量。您可以迭代添加的控件。

您可能会问“具体是哪个控件?它们还没有添加!”

嗯,这就是为什么要在 ngOnInit 中以编程方式添加这些控件的原因:

ngOnInit() {
this.testForm = new FormGroup({
arrs: new FormArray([])
}
);

for (let i = 0; i < this.count; i++) {
const control = new FormControl(null, Validators.required);
(<FormArray>this.testForm.get('arrs')).push(control);
}

this.disableInputs();
}

这是启动 FormArray 的正确语法,然后在 for 循环内创建一个初始控件并将新创建的控件推送到您的数组。

注意:有一个 disableInputs() 函数调用。这也是您以编程方式禁用输入的地方:

  disableInputs() {
(<FormArray>this.testForm.get('arrs'))
.controls
.forEach(control => {
control.disable();
})
}

工作示例:stackblitz

关于javascript - 如何在 Angular 4 的 FormArray 中禁用 FormControl,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51155763/

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