使用Angular 6导航到特定选项卡

时间:2019-06-15 17:57:29

标签: angular

我正在使用查询参数导航到组件之间的特定选项卡。接收组件(需要检查查询参数)不断返回错误:

Cannot set property active of undefined

在一个组件中,我有以下html。

<button *ngIf="isLoggedInUser" style="position: absolute; right: 0" class="btn btn-link btn-sm"
            [routerLink]="['/users/' + auth.currentUser.id + '/edit']" [queryParams]="{tab: 2}">
            <i class="fas fa-pen"></i>
</button>

在编辑组件(检查查询参数的组件)中,我使用ActivatedRoute将其保存在ngOnInit中。

this.router.queryParams.subscribe(params => {
  const selectedTab = params["tab"];
  console.log(this.editProfileTabs);
  this.editProfileTabs.tabs[
    selectedTab > 0 ? selectedTab : 0
  ].active = true;
});

当我尝试时...我在控制台中得到了它:

core.js:1673 ERROR TypeError: Cannot set property 'active' of undefined

有什么想法吗?我认为三元组将处理空/未定义的内容。

我已经在控制台上记录了选项卡集,并且它确实记录了该html组中的选项卡。

enter image description here

2 个答案:

答案 0 :(得分:0)

参考变量在ngAfterViewInit()生命周期挂钩下加载到组件中。因此,如果要在“ .ts”中访问它,请在ngAfterViewInit()下进行。

ngAfterViewInit() {
    this.router.queryParams.subscribe(params => {
        this.editProfileTabs.tabs[selectedTab > 0 ? selectedTab : 0].active = true;
    });
}

在开发模式下,angular会进行两次检查,因此,如果更改在ngAfterViewInit()下绑定到HTML的属性,则在第二次检查中会出现类似以下错误:

  

ExpressionChangedAfterItHaHasBeenCheckedError

要解决此问题,应手动运行更改检测。在组件中注入ChangeDetectorRef并像这样使用它:

constructor(private _cdr: ChangeDetectorRef) {
    .....
}

ngAfterViewInit() {
    this.router.queryParams.subscribe(params => {
        this.editProfileTabs.tabs[selectedTab > 0 ? selectedTab : 0].active = true;
        this._cdr.detectChanges()
    });
}

答案 1 :(得分:0)

对我来说,这段代码

ngAfterViewInit() {    
    this.route.queryParams.subscribe(params => {
        const selectedTab = params["tab"];
        this.editProfileTabs.selectedIndex = selectedTab > 0 ? selectedTab : 0;
    });
}
相关问题