[英]Show hide text box when specific option is selected from dropdown inside dynamic form Angular
我有一個表單,用戶可以在one/more
click
添加按鈕添加one/more
地址div。
我想如果用戶從下拉列表中選擇options=5
,想要在該特定地址 Div 中顯示和隱藏文本框。
組件代碼
get contactFormGroup() {
return this.form.get('Array') as FormArray;
}
ngOnInit() {
this.form= this.fb.group({
Array: this.fb.array([])
});
}
createContact(): FormGroup {
return this.fb.group({
ABC: [null, Validators.compose([Validators.required])],
Test: [null, Validators.compose([Validators.required])]
});
}
addContact() {
this.Group.push(this.createContact());
}
showValue(event) {
const selectedValue = event;
if (selectedValue === '5') {
this.showValuetxtbox = true;
} else {
this.showValuetxtbox = false;
}
}
當您循環添加 div 時,您可以在下拉列表中使用模板引用變量。 例如 #select 然后在 *ngIf 中引用它:
<form [formGroup]="addExpressionform">
<div formArrayName="expressionArray">
<div *ngFor="let item of contactFormGroup.controls; let i = index;" [formGroupName]="i">
<carbon-dropdown #select
(optionSelected)="showValue($event)"
[formControlN]="'UOM'"
[options]="listOptions" [formGroup]="item"
name="UOM"
>
</carbon-dropdown>
<carbon-text-input *ngIf="select.value == 5"
[formControlN]="'Value'"
[formGroup]="item"
name="Value"
>
</carbon-text-input>
<carbon-button type="primary" (click)="submit()" id="save-parameter">Save</carbon-button>
</div>
</div>
</form>
看看這個 Stackblitz,它在Angular 文檔中被引用,可以作為你想要實現的樣板。
您應該通過為每個問題創建不同的class
來隔離所有可能的問題類型,以便您可以對數據進行整形,然后使用ngSwitch
地動態創建 HTML。
問題基類:
export class QuestionBase<T> {
controlType: string;
value: T;
key: string;
label: string;
// etc
constructor(options) {
// constructor logic
}
}
基類固有的一些特殊類
import { QuestionBase } from './question-base';
export class SpecialQuestion extends QuestionBase<string> {
controlType = 'specialQuestion';
type: string;
// special Question
specialValue: string;
constructor(options) {
super(options);
this.type = options['type'] || '';
}
}
然后,一個問題組件:
<div [formGroup]="form">
<label>{{question.label}}</label>
<div [ngSwitch]="question.controlType">
// controls logic
<input *ngSwitchCase="'textbox'" >
<select *ngSwitchCase="'specialQuestion'"></select>
</div>
</div>
然后將其放入一個容器組件中,在其中循環遍歷整個問題數組。
這樣,您的代碼將在未來證明和可重用,因為您在未來向表單添加/更改功能。 您不必創建意大利面條以滿足邊緣情況要求,例如額外的輸入字段。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.