在 Angular 中使用 ViewChild 訪問子組件、指令或 DOM 元素的操作方法
簡(jiǎn)介
本文將向您介紹 Angular 的 ViewChild
裝飾器。
在某些情況下,您可能希望從父組件類中訪問指令、子組件或 DOM 元素。ViewChild
裝飾器返回與給定指令、組件或模板引用選擇器匹配的第一個(gè)元素。
先決條件
如果您想要跟隨本教程進(jìn)行操作:
- 考慮安裝
@angular/cli
。 - 使用
@angular/cli
創(chuàng)建一個(gè)新項(xiàng)目,以測(cè)試ViewChild
在其中的功能。
本教程已經(jīng)驗(yàn)證過可以在 @angular/core
v13.0.2 和 @angular/cli
v13.0.3 下使用。
使用 ViewChild 與指令
ViewChild
使得訪問指令成為可能。
假設(shè)您有一個(gè) SharkDirective
。該指令將查找具有屬性 appShark
的元素,并在元素的文本前面添加單詞 "Shark"
。
理想情況下,您將使用 @angular/cli
來 generate
您的指令:
ng generate directive shark --skip-tests
此命令將創(chuàng)建一個(gè) shark.directive.ts
文件,并將該指令添加到 app.module.ts
:
import { SharkDirective } from './shark.directive'; ... @NgModule({ declarations: [ AppComponent, SharkDirective ], ... })
然后,使用 ElementRef
和 Renderer2
來重寫文本。將 shark.directive.ts
的內(nèi)容替換為以下內(nèi)容:
import { Directive, ElementRef, Renderer2 } from '@angular/core'; @Directive( { selector: '[appShark]' } ) export class SharkDirective { creature = 'Dolphin'; constructor(elem: ElementRef, renderer: Renderer2) { let shark = renderer.createText('Shark '); renderer.appendChild(elem.nativeElement, shark); } }
接下來,在組件模板中的一個(gè)包含文本的 span
中添加一個(gè) appShark
屬性。將 app.component.html
的內(nèi)容替換為以下內(nèi)容:
<span appShark>Fin!</span>
在瀏覽器中查看應(yīng)用程序時(shí),將在元素的內(nèi)容之前呈現(xiàn)單詞 "Shark"
:
Shark Fin!
現(xiàn)在,您還可以訪問 SharkDirective
的 creature
實(shí)例變量,并使用其值設(shè)置一個(gè) extraCreature
實(shí)例變量。將 app.component.ts
的內(nèi)容替換為以下內(nèi)容:
import { Component, ViewChild, AfterViewInit } from '@angular/core'; import { SharkDirective } from './shark.directive'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements AfterViewInit { extraCreature!: string; @ViewChild(SharkDirective) set appShark(directive: SharkDirective) { this.extraCreature = directive.creature; }; ngAfterViewInit() { console.log(this.extraCreature); // Dolphin } }
此代碼使用了一個(gè) setter 來設(shè)置 extraCreature
變量。請(qǐng)注意,它等待 AfterViewInit
生命周期鉤子來訪問變量,因?yàn)檫@是子組件和指令可用的時(shí)候。
在瀏覽器中查看應(yīng)用程序時(shí),您仍將看到 "Shark Fin!"
消息。但是,在控制臺(tái)日志中,它將顯示:
Dolphin
父組件能夠訪問指令的值。
使用 ViewChild 與 DOM 元素
ViewChild
使得訪問具有模板引用變量的本機(jī) DOM 元素成為可能。
假設(shè)您在模板中有一個(gè)帶有 #someInput
引用變量的 <input>
。將 app.component.html
的內(nèi)容替換為以下內(nèi)容:
<input #someInput placeholder="Your favorite sea creature">
現(xiàn)在,您可以使用 ViewChild
訪問 <input>
并設(shè)置 value
。將 app.component.ts
的內(nèi)容替換為以下內(nèi)容:
import { Component, ViewChild, AfterViewInit, ElementRef } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements AfterViewInit { @ViewChild('someInput') someInput!: ElementRef; ngAfterViewInit() { this.someInput.nativeElement.value = 'Whale!'; } }
當(dāng) ngAfterViewInit
觸發(fā)時(shí),<input>
的值將被設(shè)置為:
Whale!
父組件能夠設(shè)置子 DOM 元素的值。
使用 ViewChild 與子組件
ViewChild
使得訪問子組件并調(diào)用子組件可用的方法或訪問實(shí)例變量成為可能。
假設(shè)您有一個(gè) PupComponent
。
理想情況下,您將使用 @angular/cli
來 generate
您的組件:
ng generate component pup --flat --skip-tests
此命令將創(chuàng)建 pup.component.ts
、pup.component.css
和 pup.component.html
文件。并將該組件添加到 app.module.ts
:
import { PupComponent } from './pup.component'; ... @NgModule({ declarations: [ AppComponent, PupComponent ], ... })
然后,在 PupComponent
中添加一個(gè)返回消息的 whoAmI
方法:
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-pup', templateUrl: './pup.component.html', styleUrs: ['./pup/component.css'] }) export class PupComponent implements OnInit { constructor() { } whoAmI() { return 'I am a pup component!'; } ngOnInit(): void { } }
接下來,在應(yīng)用程序模板中引用子組件。將 app.component.html
的內(nèi)容替換為以下內(nèi)容:
<app-pup>pup works!</app-pup>
現(xiàn)在,您可以使用 ViewChild
在父組件類中調(diào)用 whoAmI
方法。將 app.component.ts
的內(nèi)容替換為以下內(nèi)容:
import { Component, ViewChild, AfterViewInit } from '@angular/core'; import { PupComponent } from './pup.component'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'], }) export class AppComponent implements AfterViewInit { @ViewChild(PupComponent) pup!: PupComponent; ngAfterViewInit() { console.log(this.pup.whoAmI()); // I am a pup component! } }
在瀏覽器中查看應(yīng)用程序時(shí),控制臺(tái)日志將顯示:
I am a pup component!
父組件能夠調(diào)用子組件的 whoAmI
方法。
結(jié)論
在本教程中,您使用了 ViewChild
來從父組件類中訪問指令、子組件和 DOM 元素。
如果引用動(dòng)態(tài)更改為新元素,ViewChild
將自動(dòng)更新其引用。
在需要訪問多個(gè)子元素的情況下,您應(yīng)該使用 ViewChildren
。
如果您想了解更多關(guān)于 Angular 的知識(shí),請(qǐng)查看我們的 Angular 專題頁面,了解練習(xí)和編程項(xiàng)目。
到此這篇關(guān)于在 Angular 中使用 ViewChild 訪問子組件、指令或 DOM 元素的操作方法的文章就介紹到這了,更多相關(guān)Angular 使用 ViewChild 內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
使用typescript開發(fā)angular模塊并發(fā)布npm包
本篇文章主要介紹了使用typescript開發(fā)angular模塊并發(fā)布npm包,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-04-04AngularJS入門教程之?dāng)?shù)據(jù)綁定用法示例
這篇文章主要介紹了AngularJS之?dāng)?shù)據(jù)綁定用法,結(jié)合實(shí)例形式分析了AngularJS基于內(nèi)置指令ng-model實(shí)現(xiàn)數(shù)據(jù)綁定的操作技巧,需要的朋友可以參考下2016-11-11Angular中使用響應(yīng)式表單的詳細(xì)步驟
Angular提供了兩種處理表單的方式模板驅(qū)動(dòng)表單和響應(yīng)式表單(也稱為模型驅(qū)動(dòng)表單),使用模板驅(qū)動(dòng)表單時(shí),模板指令被用來構(gòu)建表單的內(nèi)部表示,在本文中,您探討了如何將響應(yīng)式表單應(yīng)用于一個(gè)示例 Angular 應(yīng)用程序2024-02-02angular安裝import?echarts?from‘echarts‘標(biāo)紅報(bào)錯(cuò)解決
這篇文章主要介紹了angular安裝import?echarts?from‘echarts‘標(biāo)紅報(bào)錯(cuò)解決,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-10-10angularJS 發(fā)起$http.post和$http.get請(qǐng)求的實(shí)現(xiàn)方法
本篇文章主要介紹了angularJS 發(fā)起$http.post和$http.get請(qǐng)求的實(shí)現(xiàn)方法,分別介紹了$http.post和$http.get請(qǐng)求的方法,有興趣的可以了解一下2017-05-05使用Angular Cli如何創(chuàng)建Angular私有庫詳解
這篇文章主要給大家介紹了關(guān)于使用Angular Cli如何創(chuàng)建Angular私有庫的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-01-01關(guān)于AngularJs數(shù)據(jù)的本地存儲(chǔ)詳解
本文主要介紹了每一個(gè)獨(dú)立的JS文件或者不同的控制器如何實(shí)現(xiàn)數(shù)據(jù)的共享與交互的方法。具有一定的參考價(jià)值,下面跟著小編一起來看下吧2017-01-01AngularJS實(shí)現(xiàn)圖片上傳和預(yù)覽功能的方法分析
這篇文章主要介紹了AngularJS實(shí)現(xiàn)圖片上傳和預(yù)覽功能的方法,結(jié)合HTML5實(shí)例形式對(duì)比分析了AngularJS圖片上傳的相關(guān)操作技巧與注意事項(xiàng),需要的朋友可以參考下2017-11-11