加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Angular 中的 dom 操作(ViewChild)以及父子组件中通过 ViewChild

发布时间:2020-12-17 17:44:42 所属栏目:安全 来源:网络整理
导读:app-header #header / app-header div #myBox 我是一个dom节点 / div button (click) ="getChildRun()" 获取子组件的方法 / button /* ViewChild获取dom节点 1、模板中给dom起一个名字 div #myBox 我是一个dom节点 /div 2、在业务逻辑里面引入ViewChild impo
<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,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();
     
  }
}

效果:

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读