angular - 如果在 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-if
,this.stepper
因此结果是未定义的。这是stackblitz
我的代码的链接:
任何帮助将不胜感激。
解决方案
使用超时来转移执行,并且仅在步进器存在时才使用条件:stackblitz
setTimeout(() => this.stepper ? this.stepper.selectedIndex = 1 : null);
另外,考虑将按钮上的单击绑定到ngOnInit
(尽管您应该创建一个新函数,该函数将由按钮和 ngOnInit 调用)。还可以考虑将该超时转移到订阅中。
如果您不显示数据,那么存储它是没有意义的。
推荐阅读
- javascript - 为什么我无法捕捉到返回的响应错误?
- c++ - 错误:无法转换 'std::__cxx11::basic_string
::迭代器' - c++ - 如何建立运算符优先级?
- sql - 在 MS Access 中填充字母数字值的条件更新查询
- javascript - 如何使用 Javascript 获取结果
- python - 在python中使用列表对嵌套字典进行排序
- c++ - 以不同的方式平移同一 3D 空间中的两个对象?
- ios - Mac 和 iOS 的核心蓝牙不一致
- c++ - 会员价值在 Tick 上失去价值(c++)
- javascript - 用 JS 切换类 - 只改变实际位置