Angular 中的 dom 操作(ViewChild)以及父子組件中通過 ViewChild 調用子組件的方法


<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();
     
  }
}

效果:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM