You need to enable JavaScript to run this app. Angular页面返回设置子组件属性报Cannot set property 'status' undefined错误
优惠活动
大模型
产品
解决方案
定价
更多

Angular页面返回设置子组件属性报Cannot set property 'status' undefined错误

问题场景

实现数据筛选功能的流程为:

  • 在筛选弹窗中输入数值可正常返回查询结果
  • 筛选完成后将筛选数据存入localStorage,用于页面跳转返回时恢复原有筛选状态
  • 跳转其他页面后点击返回按钮回到筛选组件页面,从localStorage读取数据填充到筛选组件对应字段时,触发报错:

报错内容:Cannot set property 'status' of undefined at SearchUserGridComponent.autoFillAdvanceSearch

已尝试多种方案仍未解决,相关代码如下:

关联代码片段

SearchUserGridComponent.ts

@ViewChild('callDialog', { static: true }) callDialog: TemplateRef<any>;

openUserAdvancedSearchPopup() {
    let dialogRef = this.dialog.open(this.callDialog,{
        width: "80vw",
        maxWidth: "1366px",
        disableClose: true
    });
}

search-user-grid.component.html

<ng-template #callDialog let-ref>
    <div *ngIf="design?.is_advanced_search_enabled" class="advanced-search" [ngClass]="{'show-advanced-search':showAdvancedSearch}">
        <advanced-user-search-component 
            *ngIf="searchColumns?.length>0" 
            [columns]="searchColumns" 
            [dropDown]="dropDown"
            (getSearchedParams)="getSearchedParams($event)" 
            (getSearchedTerms)="getSearchedTerms($event)"
            backgroundColor="rgba(190, 190, 190, 0.4)">
        </advanced-user-search-component>
    </div>
</ng-template>

advanced-user-search.component.ts

search() {
    let params = new HttpParams();
    if (this.status != null && this.status != "A") {
        if (this.status == "AC") {
            params = params.append('isActive', "" + true)
        } else if (this.status == "I") {
            params = params.append('isActive', "" + false)
        }
    }
    if (this.passwordComplexity != null && this.passwordComplexity != "A") {
        if (this.passwordComplexity == "D") {
            params = params.append('IsDefaultPolicy', "" + true)
        } else if (this.passwordComplexity == "S") {
            params = params.append('IsDefaultPolicy', "" + false)
        }
    }
    if (this.userLockedUnlocked != null && this.userLockedUnlocked != "A") {
        if (this.userLockedUnlocked == "U") {
            params = params.append('IsLocked', "" + false)
        } else if (this.userLockedUnlocked == "L") {
            params = params.append('IsLocked', "" + true)
        }
    }
    if (this.selectedEntity && this.selectedEntity.entityId) {
        params = params.append('entities', "" + this.selectedEntity.entityId)
    }
    if (this.selectedEntityType != null) {
        params = params.append('entityTypes', "" + this.selectedEntityType)
    }
    if (this.selectedRoles != null) {
        let roleString = "";
        this.selectedRoles.forEach(role => {
            roleString = roleString + "," + role
        })
        params = params.append('roles', "" + roleString)
    }
    if (this.selectedBranch && this.selectedBranch.branchid) {
        params = params.append('branchid', "" + parseInt(this.selectedBranch.branchid));
    }
    this.getSearchedParams.emit(params);
    this.dialog.closeAll();
}

返回页面的触发逻辑

当用户点击返回按钮回到筛选页时,search-user-grid.component.ts 中以下方法会被执行:

// SearchUserGridComponent.ts
ngAfterViewInit() {
    if (this.isBack == "true" && this.design.screen_name == "searchUsers") {
        this.showAdvancedSearch = true;
        this.autoFillAdvanceSearch();
    }
}

@ViewChild("advancedSearchComponent", { static: false }) advancedSearchComponent: AdvancedUserSearchComponent;

autoFillAdvanceSearch() {
    let userSearchData = JSON.parse(localStorage.getItem("userSearchData"))
    if (userSearchData != null && userSearchData != undefined) {
        // 填充搜索关键词
        if (userSearchData["search"] == undefined || userSearchData["search"] == null) {
            this.searchTerm = "";
        } else {
            this.searchTerm = userSearchData["search"];
        }

        // 填充用户状态字段
        let status = userSearchData["isActive"];
        if (status == "true") {
            this.advancedSearchComponent.status = "AC";
        } else if (status == "false") {
            // 报错从该行抛出:无法给undefined对象的status属性赋值
            this.advancedSearchComponent.status = "I";
        } else {
            this.advancedSearchComponent.status = "A";
        }
        // 后续其他字段填充逻辑...
    }
}
报错原因

触发报错的核心是this.advancedSearchComponent的取值为undefined,具体由四个问题共同导致:

  • 模板引用不匹配:@ViewChild("advancedSearchComponent") 依赖模板引用变量匹配组件实例,但在<advanced-user-search-component>标签上没有添加对应的#advancedSearchComponent标识,Angular无法定位到组件实例。
  • 渲染逻辑矛盾:高级搜索组件嵌套在MatDialog的ng-template #callDialog内部,只有调用dialog.open()方法触发Dialog打开、模板被插入DOM后,组件才会被实例化。原有代码仅设置showAdvancedSearch变量控制CSS类,没有触发Dialog打开操作,组件永远不会被挂载到DOM上。
  • 执行时序错误:ngAfterViewInit钩子触发时,Dialog未打开、高级搜索组件未初始化,此时直接调用填充逻辑,必然出现实例为undefined的问题。
  • 额外渲染阻断:高级搜索组件外层有*ngIf="searchColumns?.length>0"、*ngIf="design?.is_advanced_search_enabled"的条件判断,组件初始化阶段这些变量可能未完成赋值,进一步阻断组件渲染。
解决方案
    1. 补全模板引用标识,让ViewChild能正确匹配组件实例
      修改search-user-grid.component.html中的高级搜索组件标签,添加#advancedSearchComponent引用:
    <advanced-user-search-component 
        #advancedSearchComponent
        *ngIf="searchColumns?.length>0" 
        [columns]="searchColumns" 
        [dropDown]="dropDown"
        (getSearchedParams)="getSearchedParams($event)" 
        (getSearchedTerms)="getSearchedTerms($event)"
        backgroundColor="rgba(190, 190, 190, 0.4)">
    </advanced-user-search-component>
    
    1. 调整执行时序,先打开Dialog触发组件渲染,再执行数据填充
      修改ngAfterViewInit中的逻辑,移除直接调用autoFillAdvanceSearch()的代码,先打开Dialog,等Dialog完全打开、内部组件初始化完成后再执行填充:
    ngAfterViewInit() {
        if (this.isBack == "true" && this.design.screen_name == "searchUsers") {
            this.showAdvancedSearch = true;
            // 打开Dialog触发高级搜索组件渲染
            const dialogRef = this.dialog.open(this.callDialog,{
                width: "80vw",
                maxWidth: "1366px",
                disableClose: true
            });
            // Dialog完全打开后再执行数据填充
            dialogRef.afterOpened().subscribe(() => {
                this.autoFillAdvanceSearch();
            })
        }
    }
    
    1. 增加空值兜底判断,避免渲染时序问题导致的报错
      在autoFillAdvanceSearch()方法开头增加实例校验,如果组件未初始化完成,延迟重试,直到实例存在再执行填充逻辑:
    autoFillAdvanceSearch() {
        // 组件实例未初始化时延迟重试
        if (!this.advancedSearchComponent) {
            setTimeout(() => this.autoFillAdvanceSearch(), 100);
            return;
        }
        let userSearchData = JSON.parse(localStorage.getItem("userSearchData"))
        if (userSearchData != null && userSearchData != undefined) {
            // 原有字段填充逻辑保持不变
        }
    }
    

内容的提问来源于stack exchange,提问作者Poojan Pandya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.23 03:57:04