首页 > 解决方案 > 如果在 Angular 中,则在 dom 中的 ViewChild

问题描述

我正在尝试获取对 dom-if using 内部元素的引用ViewChild。实际上我正在使用mat-stepper并想直接导航到第二步。以下是我的代码片段;

.html

<mat-vertical-stepper  #stepper *ngIf="showStepper">

组件.ts

 @ViewChild('stepper') stepper: MatStepper;
  constructor() { }

  ngOnInit() {
    this.firstFormGroup = new FormGroup({
      firstCtrl: new FormControl(null, [Validators.required])
    });
    this.secondFormGroup = new FormGroup({
      secondCtrl: new FormControl(null, [Validators.required])
      
    });


                this.stepper.selectedIndex = 1;
  }

我想直接导航到第二步(第一索引)。为此,我正在使用 ViewChild,但由于 mat-stepper 在 a 内dom-ifthis.stepper因此结果是未定义的。这是stackblitz我的代码的链接:

Stackblitz 链接

任何帮助将不胜感激。

标签: angular

解决方案


使用超时来转移执行,并且仅在步进器存在时才使用条件:stackblitz

setTimeout(() => this.stepper ? this.stepper.selectedIndex = 1 : null);

另外,考虑将按钮上的单击绑定到ngOnInit(尽管您应该创建一个新函数,该函数将由按钮和 ngOnInit 调用)。还可以考虑将该超时转移到订阅中。

如果您不显示数据,那么存储它是没有意义的。


推荐阅读