Angular系列 -> @ViewChild 使用

发布时间 2023-04-25 17:26:55作者: 77工作室

@ViewChild 来获取DOM

  1. 在模板中给dom起个名字
<div #childDom>
    dom 节点
</div>
  1. 在业务逻辑中引入ViewChild
    import { ViewChild } from '@angular/core';

  2. 写在类里
    @ViewChild('childDom', { static: true }) childDom: any;

  3. ngAfterViewInit() 生命周期函数中操作dom

ngAfterViewInit() {
    let ele = this.childDom.nativeElement;
}

@ViewChild 来实现父子传值

parent.component.ts:

import { Component, ViewChild, AfterViewInit } from '@angular/core';
import { ChildComponent } from "../child/child.component";

@Component({
  selector: 'app-parent',
  template: `
    Message: {{ message }}
    <app-child></app-child>
  `,
  styleUrls: ['./parent.component.css']
})
export class ParentComponent implements AfterViewInit {

  @ViewChild(ChildComponent) child;

  constructor() { }

  message:string;

  ngAfterViewInit() {
    this.message = this.child.message
  }
}

child.component.ts:

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

@Component({
  selector: 'app-child',
  template: `
  `,
  styleUrls: ['./child.component.css']
})
export class ChildComponent {

  message = 'Hola Mundo!';

  constructor() { }

}

参考链接: