我有角动态反应形式,我想根据条件显示更多场。例如:基于下拉选择,我想在表单中再显示一个动态字段。
<form *ngIf="formGroup" [formGroup]="formGroup" class="form">
<div fxLayout="column" *ngFor="let field of fields;let i=index;"
[ngSwitch]="field.type">
<mat-form-field *ngSwitchCase="'text'">
<input matInput [placeholder]="field.label"
[formControlName]="field.name" [id]="field.name">
<mat-error>{{field.error}}</mat-error>
</mat-form-field>
<mat-form-field *ngSwitchCase="'dropdown'">
<mat-select placeholder="{{field.label}}" [formControlName]="field.name"
(selectionChange)="onDropDownChange($event)">
<mat-option *ngFor="let item of field.items" [value]="item">
{{item.fact}}
</mat-option>
</mat-select>
</mat-form-field>
<button (click)="add(formGroup)">
ADD
</button>
dynamicform.component.ts
export class dynamicFormComponent implements OnInit {
formGroup: FormGroup;
fields;
ngOnInit() {
this.formGroup = this.createFormControls();
this.fields = [{
{
name:"categoryname",
error:"Please Select ",
label:"Category",
type: "text",
validation: Validators.required
},{ name:"categoryType",
error:"Please Select ",
label:"Category Type",
type: "dropdown",
items: ['cat1','cat2'],
validation: Validators.required
}]
}
onDropDownChange(event){
if(event.value === 'cat1') {
// logic to add sub category to form
}
createControlForm() {
let fm = {};
this.fields.forEach((f) => {
fm[f.name] = new FormControl('',
this.validators(f.validation));
});
}
}
我能够使用类别名称和类别类型生成表单。现在,我需要根据下拉选择生成另一个字段子类别
答案 0 :(得分:2)
Angular表单API提供了称为disable属性的功能,该功能将从表单中排除formcontrol,我们可以手动启用formcontrol
component.ts
this.form = this.fb.group({
cName:'',
cType:'',
extraOption:{disabled: true, value:""}
})
this.cType.valueChanges.subscribe((v)=>{
if(v == 'cat1'){
this.extraOption = true;
//Enabling the formControl Using formControl enable() method
this.form.get('extraOption').enable();
}
})