Angular 中的 dom 操作(ViewChild)以及父子组件中通过 ViewChild 调用子组件的方法
2024-08-29 22:38:33
<app-header #header></app-header> <div #myBox> 我是一个dom节点
</div> <button (click)="getChildRun()">获取子组件的方法</button>
/* ViewChild获取dom节点
1、模板中给dom起一个名字
<div #myBox>
我是一个dom节点
</div>
2、在业务逻辑里面引入ViewChild
import { Component, OnInit,ViewChild} from '@angular/core';
3、 写在类里面 @ViewChild('myBox') myBox:any;
4、ngAfterViewInit生命周期函数里面获取dom
this.myBox.nativeElement
*/ import { Component, OnInit,ViewChild} from '@angular/core'; @Component({
selector: 'app-news',
templateUrl: './news.component.html',
styleUrls: ['./news.component.scss']
})
export class NewsComponent implements OnInit {
//获取dom节点
@ViewChild('myBox') myBox:any;
//获取一个组件
@ViewChild('header') header:any;
constructor() { } ngOnInit() {
} ngAfterViewInit(): void {
console.log(this.myBox.nativeElement);
this.myBox.nativeElement.style.width='100px';
this.myBox.nativeElement.style.height='100px';
this.myBox.nativeElement.style.background='red';
console.log(this.myBox.nativeElement.innerHTML);
} getChildRun(){ //调用子组件里面的方法
this.header.run(); }
}
效果:
最新文章
- 《Entity Framework 6 Recipes》中文翻译系列 (25) ------ 第五章 加载实体和导航属性之加载完整的对象图和派生类型上的导航属性
- mongodb的一些小总结
- 无线客户端框架设计(5):调用MobileAPI的设计(iOS篇)
- 01scala环境搭建和基础
- 在右键添加Cmder here选项,添加启动Cmder的快捷键
- JavaWeb解释一下什么是 servlet?
- servlet过滤器简化版
- Spring Boot 2.0 教程 - 深入SpringAplication
- [Swift]LeetCode221. 最大正方形 | Maximal Square
- sqlserver 脚本生成数据库文档
- 批量将PowerDesigner中表字段由小写变成大写
- Spark记录-阿里巴巴开源工具DataX数据同步工具使用
- CentOS 6.5下快速搭建ftp服务器[转]
- 【重要通知】本人所有技术文章转移至https://zzqcn.github.io
- PyQt5教程——介绍(1)
- APP界面框架初窥---标签导航
- rabbitmq 简单应用
- nginx学习与配置-安装与启动关闭管理
- CC2541广播机制和代码分析(未完成)
- 【题解】51nod 1203JZPLCM问题