浅谈Angular中@ViewChild的用法


本文摘自PHP中文网,作者青灯夜游,侵删。

本篇文章带大家了解一下Angular中@ViewChild,介绍一下@ViewChild的使用方法。

简单来说

个人对@ViewChild的理解就是:它是一个指代,可以通过这个指代,得到这个组件或者元素。并且我们可以使用得到的这个组件的值和方法。【相关教程推荐:《angular教程》】

为了更直观的知道它是做什么,直接上代码

通过@ViewChild获取子组件,得到子组件的值、调用子组件的方法

子组件child

1

2

3

4

content:'Zita';

changeChildCon() {

    this.content = 'Zita1111'

}

父组件parent

1

2

3

4

5

6

7

8

9

html

<app-child #ChildrenView></app-child>

 

ts

import { ViewChild } from '@angular/core';

@ViewChild('ChildrenView', { static: true }) childrenView: any;  //ChildrenView为子组件中的#后边的值,childrenView是个名称用来指代子组件

this.childrenView.content   // Zita  获取子组件中的值

this.childrenView.changeChildCon()  // 执行子组件中的方法

this.childrenView.content   // Zita1111

通过@ViewChild获取某个元素

html

1

2

3

<figure #parBele>

  我是父元素中的一个标签figure,我可以通过viewchild来获取,并且获取到我之后可以改变我的样式

</figure>

ts

1

2

3

import { ViewChild, ElementRef } from '@angular/core';

@ViewChild('parBele', { static: true }) eleRef: ElementRef;

this.eleRef.nativeElement.style.color = 'red'// 更改获取的dom元素的样式

那么,通过这段代码,你就会在页面中看到,figure标签中的字体颜色变成了红色
在这里插入图片描述

特别提醒

angular8.0之后一定要加上{ static: true } 这个属性哦,除此外,官方给这个属性的解释说明是:

元数据属性:
selector - 用于查询的指令类型或名字。
read - 从查询到的元素中读取另一个令牌。
static - True to resolve query results before change detection runs, false to resolve after change detection. Defaults to false.

对于static,意思就是:如果为true,则在运行更改检测之前解析查询结果,如果为false,则在更改检测之后解析。默认false.

阅读剩余部分

相关阅读 >>

5种Angular中组件通信的方法介绍

Angular组件学习之浅析内容投影

Angular脏值检测与vue数据劫持的区别是什么

Angular material的使用详解

Angular cli中的在线和离线安装

Angular的$watch方法详解

深入了解Angular中的component组件

Angular组件怎么进行通信?父子组件通信的2种方法

浅谈Angular中http请求模块的用法

详解Angular中的ngmodule(模块)

更多相关阅读请进入《Angular》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...