【问题标题】:Navigating to a specific tab with Angular 6使用 Angular 6 导航到特定选项卡
【发布时间】:2019-06-15 17:57:29
【问题描述】:

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

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>

在编辑组件(检查查询参数的那个)中,我在我的 ngOnInit 中使用 ActivatedRoute

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 组中的选项卡。

【问题讨论】:

  • 检查this.editProfileTabs 的内容,这可能没有您要获取的索引的值。
  • 好主意。我做到了。控制台显示选项卡。使用屏幕截图查看更新后的帖子。
  • 这个调试的问题是,控制台日志是懒惰的并且评估晚了。在queryParams 订阅下,尝试记录如下:console.log(JSON.parse(JSON.stringify(this.editProfileTabs)))
  • 啊。是的。现在标签集数组中只有 2 个标签在索引 0 和 1 处。所以索引 2 不存在。关于如何修复的想法?
  • 但是,如果适用,请遵循第一个建议。 setTimeout() 调用整个应用程序的更改检测,而 detectChanges() 将仅调用当前组件及其子组件。

标签: angular


【解决方案1】:

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

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

在开发模式下,angular 会进行两次检查,因此如果您更改绑定到ngAfterViewInit() 下的 HTML 的属性,那么在第二次检查中您将收到如下错误:

ExpressionChangedAfterItHasBeenCheckedError

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

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

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

【讨论】:

    【解决方案2】:

    对我来说这个代码

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-02-27
      • 1970-01-01
      • 1970-01-01
      • 2019-01-03
      • 2018-07-12
      • 1970-01-01
      • 2016-02-16
      相关资源
      最近更新 更多