代码之家  ›  专栏  ›  技术社区  ›  J.G.Sable

导航到具有角度6的特定选项卡

  •  0
  • J.G.Sable  · 技术社区  · 5 年前

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

    Cannot set property active of undefined

    <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>
    

    在edit组件(检查查询参数的组件)中,我在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
    

    有什么想法吗?我认为三元函数可以处理空的/未定义的东西。

    我用控制台记录了tabset,它也记录了html组中的tabs。

    enter image description here

    0 回复  |  直到 5 年前
        1
  •  1
  •   Ashish Ranjan    5 年前

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

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

    在开发模式中,angular会执行两次检查,以便在 ngAfterViewInit()

    表达式更改已检查错误

    若要解决此问题,应手动运行更改检测。注入 ChangeDetectorRef 在组件中,并按如下方式使用:

    constructor(private _cdr: ChangeDetectorRef) {
        .....
    }
    
    ngAfterViewInit() {
        this.router.queryParams.subscribe(params => {
            this.editProfileTabs.tabs[selectedTab > 0 ? selectedTab : 0].active = true;
            this._cdr.detectChanges()
        });
    }
    
        2
  •  0
  •   Violet    5 年前

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