首页 > 解决方案 > 多次调用 ngAfterViewInit()?

问题描述

我的应用程序使用了我分解的材料步进器,以便能够在多个组件中调用它。

我希望默认启用此步进器的第一个字段的焦点。我做了这样的事情,但只有当我启动应用程序或刷新时。一旦我在应用程序中四处走动并转到使用此步进器的页面,我就会失去这种专注。

这是不起作用的步进器的代码:

Html(仅第一个字段)

<mat-vertical-stepper class="vertical-stepper" [linear]="isLinear" #stepper (selectionChange)="onChange($event)">
      <mat-step [stepControl]="firstFormGroup" label="Scannez une référence">
        <form [formGroup]="firstFormGroup">
          <ng-template matStepLabel>{{ 'ZONE.CODE_BARRE_REF' | translate }}</ng-template>
          <div class="flexInput">
            <mat-form-field appearance="outline" class="mat-form-zone">
              <input matInput id="input0" autocomplete="off" formControlName="reference"
                placeholder="{{ 'ZONE.CODE_BARRE_REF_PLACEHOLDER' | translate }}" required>
            </mat-form-field>
              <button mat-mini-fab color="primary" (click)="onCheckRef()" matStepperNext aria-label="">
                <mat-icon>done</mat-icon>
              </button>
          </div>
        </form>
      </mat-step>

和 ts :

@ViewChild('stepper') stepper: MatStepper;
 
  constructor(private formBuilder: FormBuilder,
    private rayonService: SharedRayonService) {
  }
 
  ngOnInit() {
    this.initStepperForm();
  }
 
  ngAfterViewInit() {
    this.setFocus();
  }
 
  onChange(event) {
    let index = String(event.selectedIndex);
    this.targetInput = 'input' + index;
    if (index === "0") this.rayonService.isDisplayProductSubject.next(false);
    else if (index === "1") this.rayonService.isDisplayProductSubject.next(true);
    this.setFocus();
  }
 
  setFocus() {
    let targetCurrentInput = document.getElementById(this.targetInput);
    console.log(targetCurrentInput);
    setTimeout(function waitTargetElem() {
      if (document.body.contains(targetCurrentInput)) {
        targetCurrentInput.focus();
      } else {
        setTimeout(waitTargetElem, 100);
      }
    }, 100);
  }

我在这样的几个组件中调用此代码:

<app-stepper></app-stepper>

如何恢复预期的行为(关注组件每次调用中的第一个字段)?

标签: angularlifecycleangular-material-stepper

解决方案


推荐阅读