Angular : 你真的懂@ViewChild吗

Posted 技术农夫

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Angular : 你真的懂@ViewChild吗相关的知识,希望对你有一定的参考价值。

点击上方 “公众号” 可以订阅哦!


01

装饰器

Angular : 你真的懂@ViewChild吗

 

装饰器(Decorators):

在类的声明及成员上通过元编程语法添加标注提供了一种方式。


可以理解为一种补充成员变量成分的方式,注入式的变量初始化,不过比一般的赋值不同的是,这个成员变量往往指的是指令、组件、DOM等复杂变量。


看看Angular的@ViewChild是如何做的吧


Angular : 你真的懂@ViewChild吗

02

@V iewC hild
Angular : 你真的懂@ViewChild吗


@ViewChild是属性装饰器,装饰器的一种,用于配置一个视图查询。变更检测器会在视图的 DOM 中查找能匹配上该选择器的第一个元素或指令。如果视图的 DOM 发生了变化,出现了匹配该选择器的新的子节点,该属性就会被更新。


如何使用?

先看看她的构成:

元数据属性:

  • selector - 用于查询的指令/组件类型或模板变量名。

  • read - 从查询到的元素中读取另一个元素。


什么是模板变量名?

就是一种被用在dom指令中来标记该dom元素的名称。比如:

<div #cba>cba</div>


那么这条dom就可以被@ViewChild轻松捕获了。如:

export class AppComponent implements AfterViewInit { /**** DOM节点对应的 ****/ // DOM节点只能使用模板应用变量来找到 @ViewChild('cba') cbaDom: ElementRef; // 找到第一个符合条件的节点
ngAfterViewInit(): void { // DOM节点 console.log(this.cbaDom.nativeElement); }}


是的,这不难理解,读到这里,你已经掌握了她的一半特性,接下来就是堆叠她的余下功能。

Angular : 你真的懂@ViewChild吗


Angular : 你真的懂@ViewChild吗


应用在DOM、Component、Directive。


import {AfterViewInit, Component, ElementRef, ViewChild} from '@angular/core';
@Component({ selector: 'app-root', template: ` <!-- view child dom --> <div #domLabel> abc </div> `, styleUrls: ['./app.component.less']})export class AppComponent implements AfterViewInit { // DOM节点只能使用模板应用变量来找到 @ViewChild('domLabel') domLabelChild: ElementRef;   // 第一个符合条件的节点
ngAfterViewInit(): void { // DOM节点 console.log(this.domLabelChild.nativeElement); }}


如果出现多条,那么就要使用@ViewChildren,并且使用Angular提供的QueryList<TYPE>来捕获完整的内容列表。比如这样:

import {AfterViewInit, Component, ElementRef, QueryList, ViewChild, ViewChildren} from '@angular/core';import {ChildComponent} from './child.component';
@Component({ selector: 'app-root', template: ` <!-- view child for Component --> <app-child #appChild></app-child> <app-child></app-child> `, styleUrls: ['./app.component.less']})export class AppComponent implements AfterViewInit { @ViewChild('appChild') componentChild: ChildComponent;   // 模板变量名获取 @ViewChild(ChildComponent) componentChildByType: ChildComponent;   // 通过组件类型获取 @ViewChild('appChild', {read: ElementRef}) componentChildElement: ElementRef; // 直接子组件对应的DOM @ViewChildren(ChildComponent) componentChildList: QueryList<ChildComponent>;   // 所有的ChildComponent组件
ngAfterViewInit(): void { // DOM节点 console.log(this.componentChild); if (this.componentChildList != null && this.componentChildList.length !== 0) { this.componentChildList.forEach(elementRef => console.log(elementRef)); } }}


就是这样。


限于篇幅,下节继续。

Angular : 你真的懂@ViewChild吗
Angular : 你真的懂@ViewChild吗

GitHub应用指南专属小程序

专属工程师的服务指南


好文章    点在看

以上是关于Angular : 你真的懂@ViewChild吗的主要内容,如果未能解决你的问题,请参考以下文章

你真的懂 ajax 吗?

你真的懂Redis的5种基本数据结构吗?

软件测试52讲-01 | 你真的懂测试吗?

你真的懂Redis的5种基本数据结构吗?

你真的懂语音特征吗?

你真的懂Java的ArrayList吗?