angular dom_Angular 8 DOM查詢:ViewChild和ViewChildren示例

angular dom

The @ViewChild and @ViewChildren decorators in Angular provide a way to access and manipulate DOM elements, directives and components. In this tutorial, we'll see an Angular 8 example of how to use the two decorators.

Angular中的@ViewChild@ViewChildren裝飾器提供了一種訪問和操作DOM元素,指令和組件的方式。 在本教程中,我們將看到一個如何使用兩個裝飾器的Angular 8示例。

You can use ViewChild if you need to query one element from the DOM and ViewChildren for multiple elements.

如果您需要查詢DOM中的一個元素,而ViewChildren需要多個元素,則可以使用ViewChild

We'll be using an online development IDE available from https://stackblitz.com/ so you don't need to set up your local development machine for Angular at this point.

我們將使用可從https://stackblitz.com/獲得的在線開發IDE,因此此時您無需為Angular設置本地開發機器。

Head over to Stackblitz, sign in with your GitHub account and choose an Angular workspace:

前往Stackblitz,使用您的GitHub帳戶登錄并選擇Angular工作區:

You should be presented with an online IDE with an Angular 8 project

應該為您提供帶有Angular 8項目的在線IDE

Our Angular project contains the usual App component and a child component called HelloComponent and defined in the src/app/hello.component.ts file with the following code:

我們的Angular項目包含常用的App組件和一個名為HelloComponent的子組件,并在src/app/hello.component.ts文件中使用以下代碼定義:

import { Component, Input } from '@angular/core';@Component({selector: 'hello',template: `<h1>Hello !</h1>`,styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent  {@Input() name: string;
}

The component accepts a name property and uses an inline template which simply displays the value passed via the name property from the parent component.

該組件接受一個name屬性,并使用一個內聯模板,該模板僅顯示通過name屬性從父組件傳遞的值。

In the component decorator, we used hello as the selector for the component so in the the HTML template of the App component defined in the src/app/app.component.htmlfile, we include the child component using the following code:

在組件裝飾器中,我們使用hello作為組件的選擇器,因此在src/app/app.component.html文件中定義的App組件HTML模板中,我們使用以下代碼包含子組件:

<hello name=""></hello>
<p>Start editing to see some magic happen :)
</p>

After running our Angular application the hello component is rendered and becomes part of the DOM so we can query it just like any normal DOM element.

運行Angular應用程序后,hello組件將被渲染并成為DOM的一部分,因此我們可以像查詢任何普通DOM元素一樣查詢它。

Angular中的ViewChild是什么? (What's ViewChild in Angular?)

ViewChild is a decorator that creates a view or DOM query. According to the docs

ViewChild是創建視圖或DOM查詢的裝飾器。 根據文檔

A property decorator that configures a view query. The change detector looks for the first element or the directive matching the selector in the view DOM. If the view DOM changes, and a new child matches the selector, the property is updated.

一個屬性裝飾器,用于配置視圖查詢。 變更檢測器在視圖DOM中查找與選擇器匹配的第一個元素或指令。 如果視圖DOM更改,并且有一個新的子項與選擇器匹配,則該屬性將更新。

The decorator takes the following meta information:

裝飾器采用以下元信息:

  • selector - the selector of the element to query. This can be a directive type or a name.

    selector -要查詢的元素的選擇器。 這可以是指令類型或名稱。

  • read - read a different token from the queried elements.

    read -從查詢元件讀取的不同的令牌。

  • static - This is new in Angular 8 and indicates whether or not to resolve query results before change detection runs.

    static -這是Angular 8中的新增功能,它指示是否在運行更改檢測之前解析查詢結果。

ViewChild can take the following selectors:

ViewChild可以采用以下選擇器:

  • Classes with the @Component or @Directive decorators i.e components and directives,

    具有@Component@Directive裝飾器的類,即組件和指令,

  • Template reference variables,

    模板參考變量
  • Providers,

    提供者,
  • TemplateRef

    TemplateRef

Now, let's go back to our src/app/app.component.ts file and let's see how we can query the child component using ViewChild. First, change the code accordingly:

現在,讓我們回到src/app/app.component.ts文件,看看如何使用ViewChild查詢子組件。 首先,相應地更改代碼:

import { Component, ViewChild, AfterViewInit } from '@angular/core';import { HelloComponent } from './hello.component';@Component({selector: 'my-app',templateUrl: './app.component.html',styleUrls: [ './app.component.css' ]
})
export class AppComponent implements AfterViewInit {name = 'Angular';@ViewChild(HelloComponent, {static: false}) hello: HelloComponent;ngAfterViewInit() {console.log('Hello ', this.hello.name); }
}

In the console, you should get Hello Angular:

在控制臺中,您應該得到Hello Angular

Now, let's explain the code.

現在,讓我們解釋一下代碼。

First, we imported HelloComponent and ViewChild and AfterViewInit from the @angular/core package:

首先,我們從@angular/core包中導入了HelloComponentViewChildAfterViewInit

import { Component, ViewChild, AfterViewInit } from '@angular/core';
import { HelloComponent } from './hello.component';

Next, we create a query called hello that takes HelloComponent as the selector and has static equals to false:

接下來,我們創建一個名為hello的查詢,該查詢將HelloComponent作為選擇器,并且靜態等于false:

@ViewChild(HelloComponent, {static: false}) hello: HelloComponent;

In Angular 8, timing for ContentChild and ViewChild needs to be specified explicitly.

在Angular 8中,需要明確指定ContentChildViewChild計時。

See: ?Why do I have to specify {static: false}? Isn't that the default?

請參閱: 為什么我必須指定{static: false} ? 這不是默認值嗎?

Next, in the ngAfterViewInit() life-cycle hook, we can use the query to access the DOM element for the hello component. In our example, we accessed the name property of the component, after it's mounted in the DOM, which contains the Angular string:

接下來,在ngAfterViewInit()生命周期掛鉤中,我們可以使用查詢訪問hello組件的DOM元素。 在我們的示例中,在將組件裝入包含Angular字符串的DOM中之后,我們訪問了該組件的name屬性:

ngAfterViewInit() {console.log('Hello ', this.hello.name); }

We can access any properties and even methods from the queried component.

我們可以從查詢的組件訪問任何屬性甚至方法。

Note: View queries are set before the ngAfterViewInit callback is called.

注意 :視圖查詢是在調用ngAfterViewInit回調之前設置的。

使用模板引用查詢標準HTML元素 (Querying Standard HTML Elements with Template References)

We can also query standard HTML elements using ViewChild and template reference variables. Let's go back to our src/app/app.component.html file and change it as follows:

我們還可以使用ViewChild和模板引用變量來查詢標準HTML元素。 讓我們回到src/app/app.component.html文件并按如下所示進行更改:

<hello name=""></hello><p #pRef>Start editing to see some magic happen :)
</p>

We simply added the helloRef template reference to our hello component. Now let's change our code to access the component using its reference. Go back to the src/app/app.component.ts file and change accordingly:

我們只是將helloRef模板引用添加到了hello組件中。 現在,讓我們更改代碼以使用其引用訪問組件。 返回src/app/app.component.ts文件并進行相應更改:

import { Component, ViewChild, AfterViewInit, ElementRef } from '@angular/core';import { HelloComponent } from './hello.component';@Component({selector: 'my-app',templateUrl: './app.component.html',styleUrls: [ './app.component.css' ]
})
export class AppComponent implements AfterViewInit {name = 'Angular';@ViewChild(HelloComponent, {static: false}) hello: HelloComponent;@ViewChild('pRef', {static: false}) pRef: ElementRef;ngAfterViewInit() {console.log(this.pRef.nativeElement.innerHTML); this.pRef.nativeElement.innerHTML = "DOM updated successfully!!!"; }
}

We import ElementRef and we create a query configuration to access the <p> DOM element with the #pRef template reference as follows:

我們導入ElementRef并創建查詢配置,以使用#pRef模板引用訪問<p> DOM元素,如下所示:

@ViewChild('pRef', {static: false}) pRef: ElementRef;

Next, in the ngAfterViewInit() method we can access and modify the native DOM element using the nativeElement object of ElementRef:

接著,在ngAfterViewInit()方法我們可以訪問和使用該修改的源DOM元件nativeElement的對象ElementRef

@ViewChild('pRef', {static: false}) pRef: ElementRef;ngAfterViewInit() {console.log(this.pRef.nativeElement.innerHTML);this.pRef.nativeElement.innerHTML = "DOM updated successfully!!!"; }

This is the live example from this link.

這是此鏈接中的實時示例。

Angular中的ViewChildren是什么? (What's ViewChildren in Angular?)

ViewChildren is another property decorator which is used to query the DOM for multiple elements and return a QueryList.

ViewChildren是另一個屬性裝飾器,用于在DOM中查詢多個元素并返回QueryList 。

According to the docs:

根據文檔 :

You can use ViewChildren to get the QueryList of elements or directives from the view DOM. Any time a child element is added, removed, or moved, the query list will be updated, and the changes observable of the query list will emit a new value.

您可以使用ViewChildren從視圖DOM獲取元素或指令的QueryList。 每當添加,刪除或移動子元素時,查詢列表都將更新,并且查詢列表的可觀察到的更改將發出新值。

Let's see an example.

讓我們來看一個例子。

Go to the src/app/app.component.html file and update it as follows:

轉到src/app/app.component.html文件并按如下所示進行更新:

<hello  name="Angular 6"  ></hello>
<hello  name="Angular 7"  ></hello>
<hello  name="Angular 8"  ></hello>

We are simply diplsaying the hello component three times. Let's now query the DOM. Open the src/app/app.component.ts file and change it as follows:

我們只是簡單地三次打招呼成分。 現在讓我們查詢DOM。 打開src/app/app.component.ts文件,并進行如下更改:

import { Component, ViewChildren, AfterViewInit, QueryList } from '@angular/core';import { HelloComponent } from './hello.component';@Component({selector: 'my-app',templateUrl: './app.component.html',styleUrls: [ './app.component.css' ]
})
export class AppComponent implements AfterViewInit {name = 'Angular';@ViewChildren(HelloComponent) hellos: QueryList<any>;ngAfterViewInit() {this.hellos.forEach(hello => console.log(hello));}
}

You should this output in the console:

您應該在控制臺中顯示以下輸出:

Now, let's explain the code.

現在,讓我們解釋一下代碼。

First we import ViewChildren, AfterViewInit and QueryList from @angular/core package.

首先,我們從@angular/core包中導入ViewChildrenAfterViewInitQueryList

Next, we create a query configuration for accessing multiple DOM elements:

接下來,我們創建一個用于訪問多個DOM元素的查詢配置:

@ViewChildren(HelloComponent) hellos: QueryList<any>;

@ViewChildren returns a QueryList which stores a list of items. When the state changes Angular will automatically update this query list.

@ViewChildren返回一個QueryList ,其中存儲項目列表。 當狀態更改時,Angular將自動更新此查詢列表。

Finally, in the ngAfterViewInit() method, we can iterate over the query list and log each DOM element:

最后,在ngAfterViewInit()方法中,我們可以遍歷查詢列表并記錄每個DOM元素:

ngAfterViewInit() {this.hellos.forEach(hello => console.log(hello));}

You can find the live example from this link.

您可以從此鏈接中找到實時示例。

結論 (Conclusions)

In this tutorial, we've seen how we can access and modify the DOM in Angular 8 using ViewChild and ViewChildren decorators and a couple of other APIs like QueryListand ngAfterViewInit()

在本教程中,我們看到了如何使用ViewChildViewChildren裝飾器以及幾個其他API(例如QueryListngAfterViewInit()訪問和修改Angular 8中的DOM。

This post was originally posted in techiediaries.

該帖子最初發布在techiediaries中 。

翻譯自: https://www.freecodecamp.org/news/angular-8-dom-queries-viewchild-and-viewchildren-example/

angular dom

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/391396.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/391396.shtml
英文地址,請注明出處:http://en.pswp.cn/news/391396.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

浪潮之巔——IT產業的三大定律

http://www.cnblogs.com/ysocean/p/7641540.html轉載于:https://www.cnblogs.com/czlovezmt/p/8325772.html

DStream算子講解(一)

先把目錄列好&#xff0c;方便有條理的進行整理轉載于:https://www.cnblogs.com/leodaxin/p/7507600.html

aws 靜態網站_如何使用AWS托管靜態網站-入門指南

aws 靜態網站When I created my first portfolio last year, I based it on what I had learned from freeCodeCamp (HTML, CSS and a little JavaScript). 去年創建我的第一個投資組合時 &#xff0c;我基于從freeCodeCamp (HTML&#xff0c;CSS和一些JavaScript)中學到的知識…

leetcode 27. 移除元素(雙指針)

給你一個數組 nums 和一個值 val&#xff0c;你需要 原地 移除所有數值等于 val 的元素&#xff0c;并返回移除后數組的新長度。 不要使用額外的數組空間&#xff0c;你必須僅使用 O(1) 額外空間并 原地 修改輸入數組。 元素的順序可以改變。你不需要考慮數組中超出新長度后面…

使用TVP批量插入數據

TVP&#xff08;全稱 :Table-Valued Parameter&#xff09; 叫做表值參數(Table-Valued Parameter)是SQL2008的一個新特性。顧名思義&#xff0c;表值參數表示你可以把一個表類型作為參數傳遞到函數或存儲過程里。 第一步&#xff1a;創建一個Type類型和寫入數據的原始表結構相…

python:找出兩個列表中相同和不同的元素(使用推導式)

#接口返回值 list1 [張三, 李四, 王五, 老二] #數據庫返回值 list2 [張三, 李四, 老二, 王七]a [x for x in list1 if x in list2] #兩個列表表都存在 b [y for y in (list1 list2) if y not in a] #兩個列表中的不同元素print(a的值為:,a) print(b的值為:,b)c [x for x …

springcloud(六):配置中心git示例

隨著線上項目變的日益龐大&#xff0c;每個項目都散落著各種配置文件&#xff0c;如果采用分布式的開發模式&#xff0c;需要的配置文件隨著服務增加而不斷增多。某一個基礎服務信息變更&#xff0c;都會引起一系列的更新和重啟&#xff0c;運維苦不堪言也容易出錯。配置中心便…

寫作工具_4種加快數據科學寫作速度的工具

寫作工具I’ve been writing about data science on Medium for just over two years. Writing, in particular, technical writing can be time-consuming. Not only do you need to come up with an idea, write well, edit your articles for accuracy and flow, and proofr…

leetcode 91. 解碼方法(dp)

解題思路 記憶化搜索&#xff0c;記錄已經計算過的子問題 代碼 func numDecodings(s string) int {temp:make([]int,len(s),len(s))for i : range temp {temp[i]-1}return de(s,0,temp) } func de(s string,cur int,dp []int) int {if curlen(s){return 1}if dp[cur]!-1{re…

python數據結構與算法

2019獨角獸企業重金招聘Python工程師標準>>> http://python.jobbole.com/tag/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E4%B8%8E%E7%AE%97%E6%B3%95/ 轉載于:https://my.oschina.net/u/3572879/blog/1611369

test5

test5 轉載于:https://www.cnblogs.com/Forever77/p/11468284.html

ux和ui_閱讀10個UI / UX設計系統所獲得的經驗教訓

ux和uiAs a way to improve my UI/UX skills I decided to read the guidelines for 10 popular UI/UX design systems. In this article I will give you a concise summary of the most important concepts. 為了提高我的UI / UX技能&#xff0c;我決定閱讀10種流行的UI / UX…

大數據(big data)_如何使用Big Query&Data Studio處理和可視化Google Cloud上的財務數據...

大數據(big data)介紹 (Introduction) This article will show you one of the ways you can process stock price data using Google Cloud Platform’s BigQuery, and build a simple dashboard on the processed data using Google Data Studio.本文將向您展示使用Google Cl…

第1次作業:閱讀優秀博文談感想

摘要&#xff1a;本文介紹第1次作業的詳細內容&#xff0c;包括評分標準。 注&#xff1a;本次作業提交截止時間為UTC8(北京時間)&#xff0c;2017-9-17 22:00&#xff08;星期日&#xff09;&#xff0c;以博客發表日期為準。 1. 作業內容 閱讀一些優秀博文&#xff08;見第二…

ubuntu 16.04常用命令

ip配置&#xff1a; 終端輸入vi /etc/network/interfaces命令編輯配置文件,增加如下內容&#xff1a;         auto enp2s0    iface enp2s0 inet static    address 192.168.1.211    netmask 255.255.255.0    gateway 192.168.1.1 重啟網卡&#xf…

leetcode 28. 實現 strStr()(kmp)

實現 strStr() 函數。 給你兩個字符串 haystack 和 needle &#xff0c;請你在 haystack 字符串中找出 needle 字符串出現的第一個位置&#xff08;下標從 0 開始&#xff09;。如果不存在&#xff0c;則返回 -1 。 說明&#xff1a; 當 needle 是空字符串時&#xff0c;我們…

git 代碼推送流程_Git 101:一個讓您開始推送代碼的Git工作流程

git 代碼推送流程Im going to explain Git the way I wish someone had explained to me back when I was first learning. 我將以我希望有人在我第一次學習時向我解釋的方式來解釋Git。 Ill show how you can get started with just a few commands, and the concepts at wor…

多元時間序列回歸模型_多元時間序列分析和預測:將向量自回歸(VAR)模型應用于實際的多元數據集...

多元時間序列回歸模型Multivariate Time Series Analysis多元時間序列分析 A univariate time series data contains only one single time-dependent variable while a multivariate time series data consists of multiple time-dependent variables. We generally use mult…

字符串基本操作

1.已知‘星期一星期二星期三星期四星期五星期六星期日 ’&#xff0c;輸入數字&#xff08;1-7&#xff09;&#xff0c;輸出相應的‘星期幾 s星期一星期二星期三星期四星期五星期六星期日 d int(input(輸入1-7:)) print(s[3*(d-1):3*d]) 2.輸入學號&#xff0c;識別年級、專業…

linux:使用python腳本監控某個進程是否存在(不使用crontab)

背景&#xff1a; 需要每天定時去檢測crontab進程是否啟動&#xff0c;所以不能用crontab來啟動檢測腳本了&#xff0c;直接使用while 循環和sleep方式實現定時檢測 # coding:utf-8 import os import send_message import datetime import timecurr_time datetime.datetime.no…