Angular中使用viewchild操作dom和子组件

ViewChild获取dom节点

首先在项目中新建名为dom的组件
Angular中使用viewchild操作dom和子组件_第1张图片

步骤

  • 模板中给dom节点起名字
  • 在业务逻辑中引入viewchild
  • 通过viewchild装饰器获得dom节点
  • 在ngAfterViewInit中操作dom节点

示例

html中写一个id为myBox的节点

<h2>dom works!h2>
<div #myBox>
hello
div>

ts中引入ViewChild并使用该装饰器获取节点

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

@Component({
     
  selector: 'app-dom',
  templateUrl: './dom.component.html',
  styleUrls: ['./dom.component.scss']
})
export class DomComponent implements OnInit, AfterViewInit {
     

  // 获取view节点
  @ViewChild('myBox') myBox: any;
  constructor() {
      }

  ngOnInit(): void {
     
  }
  ngAfterViewInit(): void {
     
    console.log(this.myBox);
  }

}

查看控制台打印结果
Angular中使用viewchild操作dom和子组件_第2张图片
所以比如想要对style进行更改可以使用

this.myBox.nativeElement.style.color = 'red'; // 文字变红
console.log(this.myBox.nativeElement.innerHTML); // 获取节点文字

回忆view中对dom操作,vue一般都不对dom操作[vue中对dom操作],我之前都是通过将style变为变量,改变变量来改变样式,也可参考该文章(https://blog.csdn.net/huchangjiang0/article/details/80293586)

父组件通过ViewChid调用子组件方法

准备工作

为了演示就给dom新建一个子组件subDom(使用ng g命令),在dom组件的hmtl中加上app-sub-dom
比较无聊,所以给它加些样式
Angular中使用viewchild操作dom和子组件_第3张图片

步骤

  • 在父组件html中给子组件起名字
  • 在父组件的ts中使用viewchild获取子组件
  • this.xxx.xxxx()即可执行子组件的方法

示例

先修改父组件html,给子组件起名字

<h2>dom works!h2>
<div #myBox>
    hello
div>
<app-sub-dom #subDom>app-sub-dom>

在子组件中写一个run方法,内容是打印“我是子组件中的run方法”。
在父组件的ts中使用viewchild获取子组件

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

@Component({
     
  selector: 'app-dom',
  templateUrl: './dom.component.html',
  styleUrls: ['./dom.component.scss']
})
export class DomComponent implements OnInit, AfterViewInit {
     

  // 获取view节点
  @ViewChild('myBox') myBox: any;
  @ViewChild('subDom') subDom: any;
  constructor() {
      }

  ngOnInit(): void {
     
  }
  ngAfterViewInit(): void {
     
    console.log(this.myBox);
    this.myBox.nativeElement.style.color = 'red';
    console.log(this.myBox.nativeElement.innerHTML);

    // 调用子组件里的方法
    this.subDom.run();
  }

}

查看结果
在这里插入图片描述

在vue中,父组件要获得子组件的方法是通过ref调用的(也是通过ref获取dom节点!!!)
在这里插入图片描述
在这里插入图片描述
表面看上去也是起个名字,调用
子组件向父组件发射方法,子组件中使用$emit(xxx, 3),父组件在标签中使用@xxx='yyyy’即可。

你可能感兴趣的:(Angular,angular2,typescript)