angular中@ViewChild 的三种常用方法

//--1------ 在angular中进行dom操作
<div #dom>这是一个div</div> //放置一个锚点dom

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

@ViewChild('dom',{static:true}), eleRef:ElementRef;
//static-True表示在运行更改检测之前解析查询结果,false用于在更改检测后解析。默认为false。

// dom 操作需要在ngAfterViewInit()中进行
// ViewChild会在ngAfterViewInit()回调函数之前做完工作,也就是说你不能在构造函数中使用这个元素。
ngAfterViewInit(){
    let attr = this.eleRef.nativeElement;
    console.log(attr) //<div>这是一个div<div>
    attr.innerHTML = "@ViewChild的dom操作";
    attr.color = "red";
    console.log(attr) //<div>@ViewChild的dom操作<div>
}

//--2-------通过放置锚点获取子组件中的方法和属性
//在子组件中有一个run方法

<app-test-it #header></app-test-it> //在父组件中引入子组件并放置一个锚点 header
<button (click)="getSonFn()">点击获取子组件里面的方法</button>

import {ElementRef,ViewChild} from "angular/core";

@ViewChild('header',{static:true}), my:any;

getSonFn(){ //这是一个点击方法,点击调用这个方法。
    this.my.run();
}

//--3------通过父组件中注入子组件以获取子组件中的方法和属性
//子组件中:
<p>{{number}}</p>

number:number = 0
addNumber(){
    this.number++
}

//父组件中:
<button (click)="upCount()">number++</button>
<button (click)="downcount()">number--</button>
<app-test-it></app-test-it> //该子组件

import {ViewChild} from @angular/core;
import {TestItComponent} from './test/test-it.component";//引入子组件

@ViewChild('TestItComponent',{static: ture}) son:TestItComponent; 
  // 核心代码:用于查询子组件,并在本地创建的子组件对象 childcomponent 红注入相同属性。父组件同样有两个方法,自增和自减。

upCount(){
    this.son.addNumber();
}
downCount(){
    this.son.number--;
}


  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值