Angular 在项目中学习@ViewChild和ElementRef的使用

现在我对 @ViewChild 的了解便是,父组件中想要使用或者说操作子组件,譬如执行子组件的方法,或者说获取子组件的属性。

View就是看,Child就是孩子,看孩子,那必然是父亲看孩子

也就是说,@ViewChild 是 父组件 用来 “看” 子组件的。

[](()@ViewChild 使用一


当ViewChild传入的是子组件ChildComponent,即在父组件中注入子组件,从而获取子组件的属性或方法

childComponent.ts

import { Component } from ‘@angular/core’;

@Component({

selector:‘app-child’,

templateurl:‘bababa’,

styleUrls:‘bababab’,

})

export class ChildComponent{

childFunction(){

console.log(‘this function is from childComponent’);

}

}

parentComponent.ts

import { Component } from ‘@angular/core’;

import { ViewChild } from ‘@angular/core’;

import { ChildComponent } from ‘…/子组件的目录’;

@Component({

selector:‘app-parent’,

templateurl:‘bababa’,

styleUrls:‘bababab’,

})

export class ParentComponent{

@ViewChild(ChildComponent) child : ChildComponent;

parentFunction(){

console.log(‘this function is from parentComponent’)

this.child.childFunction();

}

}

在父组件中,要注意别忘了准备工作,导入ViewChild和子组件

import { ViewChild } from ‘@angular/core’;

import { ChildComponent } from ‘…/子组件的目录’;

此时ViewChild传入的是子组件ChildComponent,以变量child保存

@ViewChild(ChildComponent) child : ChildComponent;

这样就可以大大方方的使用子组件里的方法了。

[](()@ViewChild 使用二


当ViewChild传入的是字符串,子组件打了锚点,父组件通过锚点位置从而获得子组件的属性或方法

八九不离十,只不过使用子组件ChildComponent时要打锚点做标记,即:

<app-child #child>I am a childComponent

另外,在父组件ParentComponent的ts里是这么写的:

export class ParentComponent{

@ViewChild(‘child’) child : any; //找child这个锚点

parentFunction(){

console.log(‘this function is from parentComponent’)

this.child.childFunction();

}

}

[](()小结


近期在项目中发现:对于@ViewChild的使用,更多的是使用打锚点这种方式。有可能是我接触相关项目不够多,总结的这个规律不一定很具有典型性。

当我在项目实践时,需要去找这些父子组件之间的关系,看到有锚点如:

<app-child #child>I am a childComponent

那么我就知道,此父组件使用了 selector为 app-child 的子组件中的某种属性或方法。那么我再去搜索 app-child,再看回父组件的ts,对比查看,我就能知道父组件到底怎么操作子组件。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值