angularDom操作以及@ViewChild、执行 css3 动画

DOM操作

ngAfterViewInit(){ 
//原生JS操作
var boxDom:any=document.getElementById('box'); 
boxDom.style.color='red'; 
}
//@ViewCHild操作DOM
import { Component ,ViewChild,ElementRef} from '@angular/core';
@ViewChild('myattr') myattr: ElementRef;
let attrEl = this.myattr.nativeElement;

父子组件中通过 ViewChild 调用子组件 的方法

//调用子组件给子组件定义一个名称

// 引入 ViewChild
import { Component, OnInit ,ViewChild} from '@angular/core';
// ViewChild 和刚才的子组件关联起来
@ViewChild('footerChild') footer;
//调用子组件
run(){this.footer.footerRun(); }
//html

我是一个dom节点
//js代码 /* ViewChild获取dom节点 1、模板中给dom起一个名字
我是一个dom节点
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() } }

CSS动画

ngOnInit() {   
       //组件和指令初始化完成   并不是真正的dom加载完成
       let oBox:any=document.getElementById('box');
       console.log(oBox.innerHTML);
       oBox.style.color="red";
       //获取不到dom节点
      /*
       let oBox1:any=document.getElementById('box1');
       console.log(oBox1.innerHTML);
       oBox1.style.color="blue";
      */ 
  }
  //视图加载完成以后触发的方法    dom加载完成  (建议把dom操作放在这个里面)  
  ngAfterViewInit(){
       let oBox1:any=document.getElementById('box1');
       console.log(oBox1.innerHTML);
       oBox1.style.color="blue";
  }
hideAside(){
    //原生js获取dom节点
    var asideDom:any=document.getElementById('aside');
    asideDom.style.transform="translate(100%,0)";
 }

你可能感兴趣的:(angularDom操作以及@ViewChild、执行 css3 动画)