@ViewChild 来获取DOM
- 在模板中给dom起个名字
<div #childDom>
dom 节点
</div>
-
在业务逻辑中引入ViewChild
import { ViewChild } from '@angular/core';
-
写在类里
@ViewChild('childDom', { static: true }) childDom: any;
-
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() { }
}