angular中@ViewChild、@ViewChildren的使用

本文详细介绍了在Angular中如何使用@ViewChild和@ViewChildren装饰器来获取子组件实例和DOM节点。通过实例演示了从父组件访问子组件的方法及获取多个子组件列表的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

@ViewChild和@ViewChildren会在父组件钩子方法ngAfterViewInit调用之前赋值。

获取DOM节点

1、在html中给DOM节点设置一个模板应用变量myBox

 <div #myBox>
      我是一个div
    </div>

2、在js中引入ViewChild

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

3、通过ViewChild装饰器获取DOM节点

@ViewChild('myBox') myBox: any;

4、在生命周期里面获取DOM

 ngAfterViewInit() {
        this.myBox.nativeElement;
    }

获取子组件对象

一. 通过模板变量名

1、在子组件中定义方法

public 方法名() {
    console.log('子组件');
  }

2、在父组件html中调用子组件的时候定义一个模板变量header

 <app-header #header></app-header>

3、在父组件js中引入ViewChild

 import { ViewChild } from '@angular/core';
 import { HeaderComponent} from '子组件路径';

4、父组件通过ViewChild装饰器获取一个组件,并赋值给一个变量

   @ViewChild('header') header: HeaderComponent;

5、父组件通过变量访问子组件的方法

this.header.方法名();

二. 通过组件类

1、在父组件html中调用子组件

<app-header></app-header>

3、在父组件js中引入ViewChild

import { ViewChild } from '@angular/core';
 import { HeaderComponent} from '子组件路径';

4、父组件通过ViewChild装饰器获取一个组件,并赋值给一个变量

   @ViewChild(HeaderComponent) headerComponent: HeaderComponent;

5、父组件通过变量访问子组件的方法

   this.headerComponent.方法名();

@ViewChildren获取子组件对象列表

当选择器是TemplateRef(模版应用变量)的时候,则会获取到html里面所有的ng-template的节点

1、在父组件html中调用子组件

  <release-people-form [peopleId]="addPeopleId" (close)="handlePopCancel()" #peopleForm></release-people-form>
  <correcting-people-form [peopleId]="addPeopleId" (close)="handlePopCancel()" #peopleForm></correcting-people-form>
  <mental-people-form [peopleId]="addPeopleId" (close)="handlePopCancel()" #peopleForm></mental-people-form>

3、在父组件js中引入ViewChildren

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

4、父组件通过ViewChildren装饰器获取一个组件列表,并赋值给一个变量

@ViewChildren('peopleForm') formList: QueryList<ElementRef>;

5、父组件通过变量访问子组件的方法

   ngAfterViewInit() {
   	 console.log(this.formList); //组件对象数组
  	 console.log(this.formList.toArray()[index] as any); //获取某个对象
  }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值