检查此stackblitz 以获取工作示例。
<form [formGroup]="profileForm">
<h1>Profile Form</h1>
<div>
<label for="first-name-input">First Name</label>
<input type="text" id="first-name-input" formControlName="firstNameInput">
</div>
<div>
<label for="last-name-input">Last Name</label>
<input type="text" id="last-name-input" formControlName="lastNameInput">
</div>
<div formArrayName="optionGroups">
<div *ngFor="let $optionGroup of profileForm.controls['optionGroups'].controls; let $index=index">
<h4>Option {{ $index + 1 }} </h4>
<div [formGroupName]="$index">
<label for="select-input">Criteria</label>
<select id="{{ 'select-input' + $index }}" formControlName="selectInput">
<option value="0" disabled selected>Select a Criteria</option>
<option *ngFor="let select of selects" [value]="select.name">{{select.id}}</option>
</select>
<label [for]="'where-input-' + $index">Option</label>
<select [id]="'where-input-' + $index" formControlName="whereInput">
<option value="0" disabled selected>Select a Option</option>
<option *ngFor="let where of getWheresFor(profileForm.controls['optionGroups'].controls[$index].controls['selectInput'].value)" [value]="where.name">
{{where.id}}
</option>
</select>
<button type ="button" (click)="removeOptionGroup($index)">X</button>
</div>
</div>
</div>
<button type="button" (click)="addOptionGroup()">Add Options</button>
<div>
<button type="button" (click)="saveProfileForm()">Send</button>
</div>
</form>
<pre>
{{ profileForm.value | json }}
</pre>
重要的是,一旦您选择了“标准”,则应使用此功能刷新“选项”列表:
getWheresFor(inputStr: string): Where[] {
return this.dropdownservice
.getWhere()
.filter(item => item.selectid === inputStr);
}
像这样从你的 html 调用:
getWheresFor(profileForm.controls['optionGroups'].controls[$index].controls['selectInput'].value)"
您也可以使用$optionGroup 变量来缩短这样的表达式:
getWheresFor($optionGroup.controls['selectInput'].value)"
更新
select [id]="'where-input-' + $index"
这将为每个select 元素在DOM 中生成唯一的ID。典型的用例是 label 元素,它有一个 for 属性,如下所示:
<label [for]="'select-input' + $index">Criteria</label>
<select id="{{ 'select-input' + $index }}" formControlName="selectInput">
这个标记会生成这样的dom元素:
这样做的用途是,现在用户可以点击标签的文本,select 元素将获得焦点。