angular的viewChild和viewChildren

属性选择器,用来从模板视图上获取匹配的元素。可以在ngAfterViewInit中获取到查询的元素。
格式:

ViewChild(selector:string|Function|Type,opts?:{
   read?:any;static?:boolean}):any

1:元数据属性
selector:
用于查询指令类型或名字。

read:
告诉viewChild返回什么类型的数据,取值可以是ElementRef,TemplateRef,Component,ViewContainerRef等。

static:
默认为false,如果值为false,则是在变更检测之后解析查询结果,值为true,是在变更检测之前解析。

2:常见用法
1:同一个组件,一般不直接使用原生方法操作dom,可以借助viewChild:

<div #divDemo>abc</div>
@ViewChild('divDemo',{
   read:ElementRef}) divDemo!:ElementRef;
ngAfterViewInit(){
   
    divDemo.nativeElement.style.color = 'red';
}

2:父子组件,当我们需要获取子组件的值和方法的时候
有两种形式:一种是使用放置锚点的方法,一种是引入子组件。
2.1:放置锚点

//子组件test-child.ts
title='初始化的title值';
changeTitle():void {
   
  this.title = '改变了title';
}
//父组件app.html
<app-test-child #testChild></app-test-child>
<button (click)="changeChildTitle()">改变子组件的title值</button>
//父组件app.ts
@ViewChild('testChild')testChild!:any;
changeChildTitle():void {
   
    this.testChild.changeTitle();
}

2.2:引入子组件

import {
    TestChildComponent } from './test-child/test-child.component';
@ViewChild(TestChildComponent) testChild!:TestChildComponent;

3:问题
报ExpressionChangedAfterItHasBeenCheckedError错误,需要设置static:true

//父组件
<p>{
   {
   testChild.title}}</p>
//报错
//ERROR Error: NG0100: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'undefined'. Current value: '[object Object]'..

{ static: true } 其实就是静态查询,在ngOnInit中可用。
{ static:false } 其实就是动态查询,一般结合*ngIf使用。

viewChildren和viewChild类似,但没有static选项。
返回一个QueryList集合。

<div #divDemo>123</div> 
<div #divDemo>456</div>
@ViewChildren ('divDemo') divDemo!:QueryList<ElementRef>;
ngAfterViewInit(){
   
  this.divDemo.forEach(ele=>{
   
    console.log(ele);
  })
}

猜你喜欢

转载自blog.csdn.net/yang295242361/article/details/142126105