ViewChild inside a dom if in Angular



我正在尝试使用ViewChild获取对 dom-if 内部元素的引用。实际上我正在使用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,但是由于垫步进器位于dom-if内,因此this.stepper是未定义的。 这是我的代码stackblitz链接:

堆栈闪电战链接

任何帮助将不胜感激。

使用超时来转移执行,并使用条件仅在步进器存在时才执行此操作:堆栈闪电战

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

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

如果不显示数据,则存储数据毫无意义。

最新更新