我想根据下拉菜单中的选定选项生成表单输入文本框。
<mat-label>Options</mat-label>
<select matNativeControl name="Options" required>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
</mat-form-field>
仅在此选择框之后,根据选择的编号,一些输入字段应该存在。
以下解决方案可以为您工作。
HTML代码,
<div>
<mat-form-field>
<mat-label> Options</mat-label>
<mat-select
[(ngModel)]="selectedValue"
(selectionChange)="onSelectOption()"
>
<mat-option value="2">2</mat-option>
<mat-option value="3">3</mat-option>
<mat-option value="4">4</mat-option>
<mat-option value="5">5</mat-option>
</mat-select>
</mat-form-field>
<div *ngFor="let field of fieldsArray">
<input type="text" [value]="field" />
</div>
</div>
Component.ts代码,
selectedValue: number = 2;
fieldsArray: any[] = [];
onSelectOption() {
for(let i=1; i<=this.selectedValue; i++) {
this.fieldsArray.push(i);
}
}
您可以使用FormGroup
和FormGroup
动态生成控件:
HTML代码:
FormArray
TS代码:
FormArray
<mat-form-field>
<mat-label>Select an option</mat-label>
<mat-select [(value)]="selected" (selectionChange)="addControlsInFormArray()">
<mat-option>None</mat-option>
<mat-option value="1">1</mat-option>
<mat-option value="2">2</mat-option>
<mat-option value="3">3</mat-option>
</mat-select>
</mat-form-field>
<form [formGroup]="fg" (ngSubmit)="onSubmit()">
<div formArrayName="inputs" *ngFor="let item of fg.get('inputs').controls; let i = index;">
<div [formGroupName]="i">
<mat-form-field class="example-full-width">
<input matInput formControlName="question" placeholder="Placeholder text" value="">
</mat-form-field>
</div>
</div>
</form>
<div style="padding-top:20px">
<h2>Form Value:</h2>
{{fg.value | json}}
</div>
我建议您使用反应形式。看一下这个stackblitz import { Component } from "@angular/core";
import { FormBuilder, Validators,FormGroup,FormControl,FormArray} from "@angular/forms";
/** @title Simple form field */
@Component({
selector: "form-field-overview-example",
templateUrl: "form-field-overview-example.html",
styleUrls: ["form-field-overview-example.css"]
})
export class FormFieldOverviewExample {
fg: FormGroup;
fa: FormArray;
selected = 0;
constructor(private fb: FormBuilder) {
this.fg = this.fb.group({
inputs: this.fb.array([])
});
}
addControlsInFormArray() {
if (this.fa) {
while (this.fa.length !== 0) {
this.fa.removeAt(0);
}
}
for (var i = 0; i < this.selected; i++) {
this.fa = this.fg.get("inputs") as FormArray;
this.fa.push(this.createItem());
}
}
createItem(): FormGroup {
return this.fb.group({
question: new FormControl("")
});
}
}
,但基本上可以归结为:
组件用户界面:
Live Demo
组件逻辑:
Live Demo