首页 > 解决方案 > ngAfterViewChecked 还不够晚

问题描述

我正在使用物化作为引导程序的替代品。

我有一个问题,其中尚未加载选择的选项,在这种情况下调用物化的初始化将无法正确显示:

给定我的数据:

    @Component({
      selector: 'app-form',
      templateUrl: './form.component.html',
      styleUrls: ['./form.component.sass']
    })
    export class FormComponent implements OnInit {
      inputTest= {
        value: 1,
        choiceValues: [1,2,3,4]
      };
    }

以下html:

      <select [(ngModel)]='inputTest.value' [ngModelOptions]="{standalone: true}">
        <ng-container *ngFor="let choiceValue of inputTest.choiceValues">
          <option [ngValue]="choiceValue">{{choiceValue}}</option>
        </ng-container>
      </select>

具有以下内容:

  ngAfterViewChecked() {
    if (this.needsInitialization) {//just a guard to have the initialization once
      this.needsInitialization = false;
      
        let elems: NodeListOf<Element> = this.elementRef.nativeElement.querySelectorAll('select');
        M.FormSelect.init(elems, {});
  }

将显示(奇怪的是,所有选项都是可见的!):

在此处输入图像描述

并点击:

在此处输入图像描述

使用 setTimeout 将起作用:

      ngAfterViewChecked() {
        if (this.needsInitialization) {
          this.needsInitialization = false;
            setTimeout(() => {
              let elems: NodeListOf<Element> = this.elementRef.nativeElement.querySelectorAll('select');
              M.FormSelect.init(elems, {});
            }, 1000);
    }

在此处输入图像描述

根据:https: //angular.io/guide/lifecycle-hooks#lifecycle-event-sequence ngAfterViewChecked是ngDestroy之前的最后一个序列。但它并没有做到它所承诺的:完全加载了视图。

当 Angular 的生命周期无法正常工作时,如何使用比超时更好的方法?

标签: angularmaterializelifecycle

解决方案


推荐阅读