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.mzph.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…