
一、Angular 中的 dom 操作(原生 js)
ngAfterViewInit(){ var boxDom:any=document.getElementById('box'); boxDom.style.color='red'; }
二、Angular 中的 dom 操作(ViewChild )
import { Component ,ViewChild,ElementRef} from '@angular/core';
@ViewChild('myattr') myattr: ElementRef;
<div #myattr></div>
ngAfterViewInit(){
let attrEl = this.myattr.nativeElement;
}
import { Component, OnInit ,ViewChild} from '@angular/core';
@Component({
selector: 'app-learn-dom',
templateUrl: './learn-dom.component.html',
styleUrls: ['./learn-dom.component.scss']
})
export class LearnDomComponent implements OnInit {
#获取dom节点
@ViewChild('myBox') myBox:any;
constructor() { }
ngOnInit(): void {
//生命周期函数
//组件和指令初始化完成,并不是真正的dom加载完成
// let oBox:any=document.getElementById("box");
// console.log(oBox.innerHTML);
// oBox.style.color='red';
}
ngAfterViewInit(){
// let oBox1:any=document.getElementById('box1');
// console.log(oBox1.innerHTML);
// oBox1.style.color='blue'
console.log(this.myBox.nativeElement)
this.myBox.nativeElement.style.color='yellow'
}
}
三、父子组件中通过 ViewChild 调用子组件
的方法
1.调用子组件给子组件定义一个名称
例如在new组件调用header组件
在new.component.html中加入
<app-header #header></app-header>
在news.components.ts

在news组件引入header组件中的run()方法

悟已往之不谏,知来者之可追。
浙公网安备 33010602011771号