Materializecss select not working with angular 5

…衆ロ難τιáo~ 提交于 2021-01-27 22:58:41

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!