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.html
file, 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
包中導入了HelloComponent
和ViewChild
和AfterViewInit
:
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中,需要明確指定ContentChild
和ViewChild
計時。
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
包中導入ViewChildren
, AfterViewInit
和QueryList
。
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 QueryList
and ngAfterViewInit()
在本教程中,我們看到了如何使用ViewChild
和ViewChildren
裝飾器以及幾個其他API(例如QueryList
和ngAfterViewInit()
訪問和修改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