关于 Angular view Query 的 id 选择器问题的单步调试
問題描述
我有這樣一個 Angular Component,模板文件如下:
@Component({
selector: ‘example-app’,
template: `
<pane id=“1” *ngIf=“shouldShow”>
<pane id=“2” *ngIf="!shouldShow">
`,
})
然而運行時沒有得到期望的結果,報錯:
ERROR TypeError: Cannot read properties of undefined (reading ‘id’)
at ViewChildComp.set (ng-content.component.ts:57:27)
at ViewChildComp_Query (template.html:3:5)
at executeViewQueryFn (core.js:8758:5)
at refreshView (core.js:7437:13)
at refreshComponent (core.js:8527:13)
at refreshChildComponents (core.js:7186:9)
at refreshView (core.js:7430:13)
at refreshComponent (core.js:8527:13)
at refreshChildComponents (core.js:7186:9)
at refreshView (core.js:7430:13)
問題分析
我們點擊上圖高亮的 template.html 調用棧:
來到我們自己 Component 的模板文件,因為這是一個內聯到 Component 里的模板,所以顯示為 template.html :
通過單步調試,能發現在 refreshView 里,執行 view query 的入口邏輯:
function executeViewQueryFn(flags, viewQueryFn, component) {ngDevMode && assertDefined(viewQueryFn, 'View queries function to execute must be defined.');setCurrentQueryIndex(0);viewQueryFn(flags, component); }根據關鍵字 view query 查詢 Angular 官網,發現在 view query 里使用 id 選擇器的正確語法,并不是直接查詢 HTML 元素的 id 屬性,而是需要在 HTML 元素或者 ng-template 里使用符號 # 指定一個 id,然后將這個 id 傳入 @ViewChild:
修改之后的運行效果:
總結
view query 在父 Component 需要訪問其子 Component 的場景下特別有用。
假設有一個 alert Component:
@Component({selector: 'alert',template: `<h1 (click)="alert()">{{type}}</h1>`, }) export class AlertComponent {@Input() type: string = "success";alert() {console.log("alert");} }在我們的父 Component 里,可以定義 AlertComponent 的多個實例:
@Component({selector: 'my-app',template: `<alert></alert><alert type="danger"></alert><alert type="info"></alert>`, }) export class App {@ViewChildren(AlertComponent) alerts: QueryList<AlertComponent>ngAfterViewInit() {this.alerts.forEach(alertInstance => console.log(alertInstance));} }我們可以使用 @ViewChildren 裝飾器從宿主視圖中抓取元素。
@ViewChildren 裝飾器支持指令或組件類型作為參數,或模板變量的名稱。
當參數是組件/指令時,返回值將是組件/指令實例。
上面例子的 console.log 語句會打印 AlertComponent 的實例:
總結
以上是生活随笔為你收集整理的关于 Angular view Query 的 id 选择器问题的单步调试的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 原神教官套适合哪些角色 教官四件套有什么
- 下一篇: SAP UI5 应用开发教程之五十一 -