我想基于父级->子级->孙子级->曾孙子等模式创建类别下拉列表。
因此,如果我在屏幕上选择第一个类别下拉菜单,则应该显示第二个下拉菜单,其中包含选定类别的子类别(通过http调用)。同样,选择第二个下拉列表结果到具有填充的Grad子类别的第三个下拉菜单中。
我想过两种方式,但都具有吸引力。
第一种方法是在页面上已有下拉列表。但这仅需要具有已知级别的类别。但是我的下拉菜单可能未知。下面的示例代码受两个下拉菜单的限制。
populateSubCategory(selectedCountry) {
this.commonService.getCategories(selectedCategory).subscribe((response) => {
this.subcategories = response.categories.map((category) => {
return {id: category.id, name: category.name};
});
this.subcategories.unshift({id: "", name: "Select category"});
});
}
<select (change)="populateCategory($event.target.value)" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.category.errors }" formControlName="category">
<option *ngFor="let category of categories" [value]="category.id">{{category.name}}</option>
</select>
<select (change)="populateSubSubCategory($event.target.value)" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.subcategory.errors }" formControlName="subcategory">
<option *ngFor="let subcategory of subcategories" [value]="subcategory.id">{{subcategory.name}}</option>
</select>
第二,Angular本身提供FormArray,但是会复制第一个下拉列表,因此无法将子类别数据设置到子下拉列表中。
categories: FormArray;
ngOnInit() {
this.productForm = this.formBuilder.group({
categories: this.formBuilder.array([this.createCategory])
);
}
createCategory(): FormGroup {
return this.formBuilder.group({
category: ['', [Validators.required]]
});
}
addCategory(): void {
this.categories = <FormArray>this.productForm.controls.categories
this.categories.push(this.createCategory());
}
getChildCategories(selectedCategory) {
this.productService.getCategories(selectedCategory).subscribe((response) => {
if(response.categories.length > 0) {
this.category_list = response.data.categories.map((category_row) => {
return {id: category_row.id, name: category_row.name};
});
this.category_list.unshift({id: "", name: "Select Category"});
// HOW TO Link createCategory with above data ?
this.createCategory();
}
});
}
<div class="col-md-12" formArrayName="categories" *ngFor="let category of productForm.get('categories').controls; let i = index;">
<div class="form-group" [formGroupName]="i">
<label class="form-control-label" for="category">Category</label>
<select id="category" name="category" formControlName="category" class="form-control" (change)="getChildCategories($event.target.value)">
<option *ngFor="let category_row of category_list" [value]="category_row.id">{{category_row.name}}</option>-->
</select>
</div>
</div>