@ViewChild 是一个指代,可以通过这个指代得到这个组件或者元素、甚至可以使用这个组件的值和方法。一般父组件想要获取子组件的信息,或者调用子组件的方法时可以使用 ViewChild,这是一个单向的方法。
元数据属性
官方文档的解释:https://angular.cn/api/core/ViewChild
selector
:用于查询的指令类型或名字read
:从查询到的元素中读取另一个令牌static
:若为 true,在变更检测运行之前解析查询结果;若为 false,在变更检测之后解析。默认为 false。
使用方法
(一)、比较常见的锚点使用方法
操作逻辑:先定义子组件的值和方法,父组件的
html
调用时候,加上#锚点的名字
锚点,然后在父组件的 ts 文件中通过锚点获取子组件的值和方法。
- 定义子组件的值和方法
// export-heroes.component.html
content: any = '我是子组件原始内容'
/**
* 修改 content 的内容
* @param value 父组件传过来的 content 数值
*/
changeContent(value: any): void {
this.content = value
}
- 在父组件的
html
使用子组件,并加上锚点
<!--注意: #exportHeroes 为这里的描点,changeChild()调用子组件的方法-->
<app-export-heroes #exportHeroes></app-export-heroes>
<button (click)="changeChild()">修改按钮</button>
- 在父组件的 ts 文件中通过锚点获取子组件的值和方法。
@ViewChild('exportHeroes', { static: true }) exportHeroes: any
/**
* 调用子组件的数值和方法
*/
changeChild(): void {
this.exportHeroes.changeContent('父组件调用子组件的方法修改 content 数值')
}
- 点击前和点击按钮后的效果对比图
(二)、引入子组件的 component
结合 @ViewChild
使用
这个方法和上面不一样的点在于父组件是用过引入的子组件的 component
来调用子组件的方法的,部分代码如下:
import { ExportHeroesComponent } from './export-heroes/export-heroes.component'
@ViewChild('exportHeroes', { static: true }) exportHeroes!: ExportHeroesComponent
额外注意点
Angular8.0 之后一定要加上
{ staic: true | false }
属性
看上面官方的介绍,两个选项的区分点完全介于 变更检测运行
,那这个点要怎么理解呢?
{ static: true }
其实就是静态查询,即可以静态确定结果的查询,同时这些生命周期挂钩运行时,相关节点的更改检测已经完成,我们可以保证我们已经收集了所有可能的查询结果,一般 ngOnInit
可用。
{ static: false }
其实就是动态查询,即是无法确定结果的查询,因为这个结果需要通过运行时间值(或者是绑定值)来确定的,在可访问内容查询或者查看之后,才能获取最后的查询结果,所以一般结合 *ngIf
使用。
(一) static: true
变更检测之前解析查询结果,那么我们在获取放在 *ngIf
或者 *ngShow
的数据时,会取得 undeinded
// export-heroes.component.html
<ng-container *ngIf="students">
<tr *ngFor="let temp of students">
<td>{{ temp.id }} </td>
<td>{{ temp.name }} </td>
<td>{{ temp.gender }}</td>
</tr>
</ng-container>
--------------------------------------
// export-heroes.component.ts
students = Array.from({ length: 10 }, (v, i) => {
return {
id: `1000${i}`,
name: `王大锤${i}`,
gender: '男'
}
})
---------------------------------------
// app.component.ts
@ViewChild('exportHeroes', { static: true }) exportHeroes: any
ngOnInit() {
console.log(this.exportHeroes.students)
}
(二)static: false
变更检测之后解析查询结果,那么我们在获取放在 *ngIf
或者 *ngShow
的数据时,会取得 undeinded
// export-heroes.component.html
<ng-container *ngIf="students">
<tr *ngFor="let temp of students">
<td>{{ temp.id }} </td>
<td>{{ temp.name }} </td>
<td>{{ temp.gender }}</td>
</tr>
</ng-container>
--------------------------------------
// export-heroes.component.ts
students = Array.from({ length: 10 }, (v, i) => {
return {
id: `1000${i}`,
name: `王大锤${i}`,
gender: '男'
}
})
---------------------------------------
// app.component.ts
@ViewChild('exportHeroes', { static: false }) exportHeroes: any
ngOnInit() {
console.log(this.exportHeroes.students)
}