解决方案
为了让select初始化,我不得不延迟:
loadCategories(categories: Category[]) {
categories.forEach(
(category) => {
this.categories.push(new Category(category.id,category.name));
}
);
delay(100).then(()=> {
this.enableSelect();
});
}
我从服务器获取数据并填充数组。使用该数组,我填充<option>
的{{1}},但是materializecss没有正确显示。
正如你所看到的,我正在遵循dinamic loading的物化技巧:
您必须初始化select元素,如下所示。此外,您需要单独调用页面生成的任何动态生成的选择元素。 http://next.materializecss.com/select.html
类别-selector.component.ts
<select>
类别-selector.component.html
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();
}
}
答案 0 :(得分:0)
我知道现在有点晚了,但这对我有用:
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);
}
)
}