Materializecss select не работает с angular 5

Я получаю данные с сервера и заполняю массив. Этим массивом я заполняю <option> элемента <select>, но materializecss не отображает его должным образом.

Как видите, я следую совету материализации динамической загрузки:

Вы должны инициализировать выбранный элемент, как показано ниже. Кроме того, вам понадобится отдельный вызов для любых динамически генерируемых элементов select, которые генерирует ваша страница. 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>

person dmance    schedule 16.02.2018    source источник


Ответы (1)


Я знаю, что уже немного поздно, но у меня это сработало:

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);
      }
    )
  }
person Franj    schedule 15.04.2020