问题
I am getting data from the server and filling an array. With that array I fill the <option>
of a <select>
but materializecss is not showing it properly.
As you can see I am following the tip of materializecss of dinamic loading:
You must initialize the select element as shown below. In addition, you will need a separate call for any dynamically generated select elements your page generates. http://next.materializecss.com/select.html
category-selector.component.ts
export class CategorySelectorComponent implements OnInit {
constructor(private categoryService: CategoryService) { }
categories = [];
ngOnInit() {
this.enableSelect();
this.categoryService.getCategories().subscribe(
(result)=> {
this.loadCategories(result);
},
(error) => {
console.log(error);
}
)
}
private enableSelect() {
var elem = document.getElementById('select_categories');
var instance = M.Select.init(elem, {});
}
private loadCategories(categories: Category[]) {
categories.forEach(
(category) => {
this.categories.push(category);
}
);
this.enableSelect();
}
}
category-selector.component.html
<h5>Select category</h5>
<div class="input-field col s12">
<select id="select_categories">
<option *ngFor="let category of categories" value="{{category}}">
{{category.name}}
</option>
</select>
<label>Category</label>
</div>
回答1:
I know it's a little late but this worked for me:
ngOnInit() {
this.enableSelect();
this.categoryService.getCategories().subscribe(
(result)=> {
this.loadCategories(result);
setTimeout(() => {
($('select') as any).formSelect(); // jquery or
//var elem = document.getElementById('select_categories');
//var instance = M.Select.init(elem, {});
}, 2000);
},
(error) => {
console.log(error);
}
)
}
来源:https://stackoverflow.com/questions/48823339/materializecss-select-not-working-with-angular-5