angular - 使用 Angular 8 使用 Formbuilder Typescript 在视图中切换 FormControl
问题描述
如何使用 Typescript 而不是 html 从带有 NgIf 的 HTML DOM 视图中删除元素?寻找类似的语法。
更喜欢在 typescript 中遍历一个数组,并从视图中删除项目,而不是用 NgIf 包装所有 20 个表单控件,这似乎有点重复。
当前使用 Formbuilder,而不是 FormArray。此链接将样式显示为无,从我阅读的内容来看,这在 Angular 中并不是理想的做法。真的吗?
Angular 2 -> 如何使用 FormGroup 隐藏控件
我们有排除数组,并且更喜欢在 Typescript 中使用 foreach 禁用
也许是这样的?
这只会禁用该字段,仍显示在 html 视图中
Object.keys(this.customerForm.controls).forEach(key => {
if (this.excludeFormControlArray.indexOf(key) >= 0) {
this.customerForm.get(key).disable; // This only disables the field, still shows in html View
this.customerForm = this.formBuilder.group({
'firstName': [null, [Validators.maxLength(50), PhoneNumberValidator]],
'phoneNumber': [null, [Validators.maxLength(50), PhoneNumberValidator]],
'streetName': [null, [Validators.maxLength(50), PhoneNumberValidator]],
'emailAddress': [null, [Validators.maxLength(50), Validators.email]],
'city': [null, [Validators.required, Validators.maxLength(200)]],
'state': [null, [Validators.maxLength(200)]],
'zip':[null,[Validators.maxLength(200)]]
});
HTML
//试图防止用 ngIf 包装每个项目,项目被放置在页面上的特殊位置,由于 UX 线框规范,NgFor 并不完全可行,html/css 视图比这复杂得多,
<div class = "row">
<app-input-textbox formControlName = "firstName"></app-input-textbox>
<div class = "row">
<div class = "column">
<app-input-textbox formControlName = "emailAddress"></app-input-textbox>
</div>
<div class = "test">
<app-input-textbox formControlName = "state"></app-input-textbox>
<app-input-textbox formControlName = "zip"></app-input-textbox>
</div>
解决方案
为您创建了 stackblitz。
这里我使用自定义模型(数组)来渲染字段:
<h1>My dynamic form</h1>
<form [formGroup]="formGroup">
<div *ngFor="let input of inputList">
<label>{{ input.label }}</label>
<input type="{{ input.type }}" formControlName="{{ input.formControlName }}">
<span (click)="removeInputField(input)">Remove</span>
</div>
<div>
<button type="button" (click)="addInputField()">Add Input Field</button>
<button type="submit">Submit</button>
</div>
</form>
这是添加和删除控件的两种方法:
addInputField() {
const formControlName = prompt("FormControlName input: ");
const inputType = prompt("Type input: ");
const label = prompt("Label input: ");
const inputData = {
inputType: inputType,
formControlName: formControlName,
label: label
};
this.inputList.push(inputData);
this.formGroup.addControl(
inputData.formControlName,
this.formBuilder.control("")
);
}
removeInputField(inputField: InputField) {
this.formGroup.removeControl(inputField.formControlName);
this.inputList = this.inputList.filter(field => field !== inputField);
}
主要步骤是调用removeControl
和addControl
方法。
在您的情况下,您应该调用this.customerForm.removeControl(key)
.