.
3ss.cn

浅谈Angular中@ViewChild的用法

简单来说

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

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

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

子组件child

content:'Zita';
changeChildCon() {
	this.content = 'Zita1111'
}

父组件parent

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

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

ts

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.

怎么理解呐?

主要就在于“更改检测”这个动作的发生节点。
例如,我们经常使用到的ngIf、ngShow指令,如果子组件中加入了这些指令,而同时static为true。那么,当我们去捕获指代目标时,得到的值将是undefined

至此,鄙人针对实际项目中经常用到的@ViewChild的理解到此就Over啦…与君共勉

赞(0)
未经允许不得转载:互联学术 » 浅谈Angular中@ViewChild的用法

评论 抢沙发