This article will take you to understand @ViewChild in Angular and introduce how to use @ViewChild.
Simply put
My personal understanding of @ViewChild is: it is a reference, and you can get this component or element through this reference. And we can use the obtained values and methods of this component. [Related tutorial recommendations: "angular tutorial"]
In order to know more intuitively what it does, go directly to the code
child component child
content:'Zita'; changeChildCon() { this.content = 'Zita1111' }
parent component parent
html <app-child></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
html
<figure> 我是父元素中的一个标签figure,我可以通过viewchild来获取,并且获取到我之后可以改变我的样式 </figure>
ts
import { ViewChild, ElementRef } from '@angular/core'; @ViewChild('parBele', { static: true }) eleRef: ElementRef; this.eleRef.nativeElement.style.color = 'red'; // 更改获取的dom元素的样式
Then, through this code, you will see on the page that the font color in the figure tag becomes In red
After angular8.0Be sure to add the { static: true } attribute , in addition, the official explanation for this attribute is:
Metadata attributes:
selector - the instruction type or name used for query.
read - Read another token from the queried element.
static - True to resolve query results before change detection runs, false to resolve after change detection. Defaults to false.
For static, it means: if true, change detection is running Query results are parsed before, or after change detection if false. The default is false.
How do you understand it?
Mainly lies in the node where the action of "change detection" occurs.
For example, we often use the ngIf and ngShow instructions. If these instructions are added to the subcomponent, and static is true at the same time. Then, when we capture the referent target, the value obtained will be undefined
At this point, my understanding of @ViewChild, which is often used in actual projects, is over... Let me share with you
For more programming-related knowledge, please visit: Programming Teaching! !
The above is the detailed content of A brief discussion on the usage of @ViewChild in Angular. For more information, please follow other related articles on the PHP Chinese website!