迁移至Angular 13后出现Uncaught DOMException问题求助
Angular 13迁移后ngb-accordion出现querySelector无效选择器错误
我的Angular项目使用Bootstrap 4.6.2,其中一个组件包含带ngb-accordion的表格。迁移至Angular 13前一切正常,但现在导航到该组件页面时,控制台出现以下错误:
Uncaught DOMException: Failed to execute 'querySelector' on 'Element': '#4bdecde7-0564-475c-a160-655206d24c9e' is not a valid selector. at t._getPanelElement (http://localhost:4200/main.js:1:347916) at http://localhost:4200/main.js:1:346729 at Array.forEach (<anonymous>) at qf.forEach (http://localhost:4200/main.js:1:91610) at Nt._next (http://localhost:4200/main.js:1:346704) at Nt.__tryOrUnsub (http://localhost:4200/main.js:1:5045) at Nt.next (http://localhost:4200/main.js:1:4286) at ae._next (http://localhost:4200/main.js:1:3479) at ae.next (http://localhost:4200/main.js:1:3253) at lP._next (http://localhost:4200/main.js:1:181212)
该错误不影响导航及折叠面板的开关功能,但希望消除此报错。怀疑是版本兼容问题,项目package.json依赖片段如下:
"dependencies": { "@angular/animations": "^13.4.0", "@angular/common": "~13.4.0", "@angular/compiler": "~13.4.0", "@angular/core": "~13.4.0", "@angular/forms": "^13.4.0", "@angular/localize": "^13.4.0", "@angular/platform-browser": "~13.4.0", "@angular/platform-browser-dynamic": "~13.4.0", "@angular/router": "~13.4.0", "@angular/service-worker": "^13.4.0", "@ng-bootstrap/ng-bootstrap": "^10.0.0", "@types/file-saver": "^2.0.7", "bootstrap": "^4.6.2", "file-saver-es": "^2.0.5", "font-awesome": "^4.7.0", "jquery": "^3.4.1", "ngx-toastr": "^13.2.1", "node-pre-gyp": "^0.12.0", "popper.js": "^1.14.3", "rxjs": "^6.5.5", "source-map": "^0.8.0-beta.0", "tslib": "^2.6.2", "zone.js": "^0.11.4" }, "devDependencies": { "@angular-devkit/build-angular": "^13.3.11", "@angular/cli": "^13.3.11", "@angular/compiler-cli": "^13.2.7", "@angular/language-service": "~13.4.0", "@types/jasmine": "^3.10.18", "@types/jasminewd2": "^2.0.13", "@types/node": "^12.20.55", "codelyzer": "^5.1.0", "jasmine-core": "~3.4.0", "jasmine-spec-reporter": "~4.2.1", "karma": "~6.4.3", "karma-chrome-launcher": "^3.1.1", "karma-coverage-istanbul-reporter": "^2.1.1", "karma-jasmine": "~2.0.1", "karma-jasmine-html-reporter": "^1.4.2", "karma-phantomjs-launcher": "^1.0.4", "protractor": "~7.0.0", "ts-node": "~8.3.0", "tslint": "^6.1.3", "typescript": "^4.4.4" }
问题原因
错误中的选择器是UUID格式(以数字开头),而CSS选择器规则明确ID选择器不能以数字开头。旧版本@ng-bootstrap/ng-bootstrap@10.0.0生成accordion面板ID时未处理这种情况,Angular 13升级后DOM查询逻辑更严格,触发了该报错。
解决步骤
升级@ng-bootstrap/ng-bootstrap到兼容版本
Angular 13对应的@ng-bootstrap兼容版本为11.x.x,执行以下命令升级:npm install @ng-bootstrap/ng-bootstrap@11 --save该版本修复了ID生成逻辑,会自动给数字开头的ID添加前缀,避免querySelector报错。
验证Bootstrap版本兼容性
Bootstrap 4.6.2与@ng-bootstrap/ng-bootstrap 11.x完全兼容,无需修改Bootstrap版本。清理缓存并重启项目
升级后清理缓存,避免旧代码残留:npm cache clean --force ng clean npm install ng serve手动指定面板ID(可选)
若升级后仍有问题,可手动给每个ngb-panel指定合法ID(不以数字开头):<ngb-accordion> <ngb-panel id="panel-user-list"> <ng-template ngbPanelTitle>用户列表</ng-template> <ng-template ngbPanelContent>用户表格内容</ng-template> </ngb-panel> </ngb-accordion>
内容的提问来源于stack exchange,提问作者Ems
相关产品推荐
相关产品推荐

