本篇文章帶大家了解一下Angular中@ViewChild,介紹一下@ViewChild的使用方法。
簡單來說
個(gè)人對(duì)@ViewChild的理解就是:它是一個(gè)指代,可以通過這個(gè)指代,得到這個(gè)組件或者元素。并且我們可以使用得到的這個(gè)組件的值和方法?!鞠嚓P(guān)教程推薦:《angular教程》】
為了更直觀的知道它是做什么,直接上代碼
通過@ViewChild獲取子組件,得到子組件的值、調(diào)用子組件的方法
子組件child
content:'Zita'; changeChildCon() { this.content = 'Zita1111' }
父組件parent
html <app-child #ChildrenView></app-child> ts import { ViewChild } from '@angular/core'; @ViewChild('ChildrenView', { static: true }) childrenView: any; //ChildrenView為子組件中的#后邊的值,childrenView是個(gè)名稱用來指代子組件 this.childrenView.content // Zita 獲取子組件中的值 this.childrenView.changeChildCon() // 執(zhí)行子組件中的方法 this.childrenView.content // Zita1111
通過@ViewChild獲取某個(gè)元素
html
<figure #parBele> 我是父元素中的一個(gè)標(biāo)簽figure,我可以通過viewchild來獲取,并且獲取到我之后可以改變我的樣式 </figure>
ts
import { ViewChild, ElementRef } from '@angular/core'; @ViewChild('parBele', { static: true }) eleRef: ElementRef; this.eleRef.nativeElement.style.color = 'red'; // 更改獲取的dom元素的樣式
那么,通過這段代碼,你就會(huì)在頁面中看到,figure標(biāo)簽中的字體顏色變成了紅色
特別提醒
angular8.0之后一定要加上{ static: true } 這個(gè)屬性哦,除此外,官方給這個(gè)屬性的解釋說明是:
元數(shù)據(jù)屬性:
selector – 用于查詢的指令類型或名字。
read – 從查詢到的元素中讀取另一個(gè)令牌。
static – True to resolve query results before change detection runs, false to resolve after change detection. Defaults to false.
對(duì)于static,意思就是:如果為true,則在運(yùn)行更改檢測之前解析查詢結(jié)果,如果為false,則在更改檢測之后解析。默認(rèn)false.
怎么理解吶?
主要就在于“更改檢測”這個(gè)動(dòng)作的發(fā)生節(jié)點(diǎn)。
例如,我們經(jīng)常使用到的ngIf、ngShow指令,如果子組件中加入了這些指令,而同時(shí)static為true。那么,當(dāng)我們?nèi)ゲ东@指代目標(biāo)時(shí),得到的值將是undefined
至此,鄙人針對(duì)實(shí)際項(xiàng)目中經(jīng)常用到的@ViewChild的理解到此就Over啦…與君共勉