Angular系列 -> @ViewChild 使用
@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() { }
}
参考链接:
本文来自博客园,作者:77工作室,转载请注明原文链接:https://www.cnblogs.com/z7luv/p/15739862.html
如果您觉得阅读本文对您有帮助,请点击一下右下方的推荐按钮,您的推荐将是我写作的最大动力!版权声明:本文为博主原创或转载文章,欢迎转载,但转载文章之后必须在文章页面明显位置注明出处,否则保留追究法律责任的权利。

浙公网安备 33010602011771号