角度问题:我试图获取用户的下拉选择的值,以便动态填充下一个下拉菜单,并仅向他们显示应基于其原始选择返回的选项。我有一个函数,它使用$ event的值,打我的JSON文件,然后返回正确的字符串以填充下一个下拉列表,但是唯一显示的是空的下拉列表。
我抛出了虚假的html来测试NgIf,并知道它的工作原理以及在登录到控制台时从我的函数返回的值。这里真的很茫然,除非我对幕后的角度一无所知,否则我应该只能将函数中的值插入NgFor并为第二个下拉菜单抛出新创建的选项
post.component.ts:
export class PostComponent implements OnInit {
rForm: FormGroup;
title: String;
description: String;
category: String;
subCategory: String;
item: String;
deathDate: Date;
claimedBy: String;
specifics: String;
selections = postOptions;
currentOptions: String[]
showSecond: boolean = false
showThird:boolean= false
currentName:String
toggleCategory(event) {
this.showSecond = true
let selectedTitle = (event.target.value);
this.currentName = event.target.getAttribute('name')
this.currentOptions = this.displaySubcategory(selectedTitle,
this.currentName);
}
displaySubcategory(str: any, dataToDisplay: String) {
let childData = {
index: 0,
options: [],
};
for (let i = 0; i <= this.selections.length; i++) {
if (str === this.selections[i].department) {
childData.index = i;
for
(let j = 0; j < this.selections[i].children.length; j++)
{
childData.options.push
(this.selections[i][`${dataToDisplay}`][j].title)
}
}
return childData.options;
}
}
post.component.html:
<div class="panel-body">
<div class="dropdown">
<select class="form-control" id="category"
(change)="toggleCategory($event)"
[(ngModel)]="this.category" name="children">
<option>scenery</option>
<option>electrical</option>
<option>material</option>
<option>etc</option>
</select>
</div>
<div *ngIf="this.showSecond">
<div class="dropdown">
<select class="form-control" id="category
(change)="toggleCategory($event)"
[(ngModel)]="currentOptions" name="item">
<div *ngFor="let item of items">
<option>{{item}}</option>
</div>
</select>
</div>
</div>
预期结果将记录到控制台并存储为this.currentOptions,NgIf条件触发并呈现下一个下拉列表,但似乎没有任何内容传递给下拉列表。我是否需要异步设置? NgFor是否在事件或DOM呈现时触发?
答案 0 :(得分:2)
请勿将您的<option>
包装在div中。它应该是<ng-container>
<select class="form-control" id="category
(change)="toggleCategory($event)"
[(ngModel)]="currentOptions" name="item">
<ng-container *ngFor="let item of items">
<option>{{item}}</option>
</ng-container>
</select>