日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

关于 Angular view Query 的 id 选择器问题的单步调试

發布時間:2023/12/19 编程问答 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 关于 Angular view Query 的 id 选择器问题的单步调试 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

問題描述

我有這樣一個 Angular Component,模板文件如下:
@Component({
selector: ‘example-app’,
template: `
<pane id=“1” *ngIf=“shouldShow”>
<pane id=“2” *ngIf="!shouldShow">

<button (click)="toggle()">Toggle</button> <div id="panel 1?" #pane999>1</div> <div id="panel 2?" pane>2</div> <div>Selected: {{selectedPane}}</div>

`,
})

在其 Component 實現里,我期望通過 `@ViewChild`,在運行時拿到 id 為 `panel 1?` 的 div 元素的實例。```typescript export class ViewChildComp {constructor(public changeDetectorRef: ChangeDetectorRef){}@ViewChild("panel 1?")set panethis(v) {//setTimeout(()=> this.selectedPane = v.id, 0);this.selectedPane = v.id;this.changeDetectorRef.detectChanges();//Promise.resolve().then(() => this.selectedPane = v.id);}

然而運行時沒有得到期望的結果,報錯:

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 选择器问题的单步调试的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。