原生js的操作示例
app.component.html
<h1>
{{ msg }}
h1>
<h2>DOM操作演示h2>
<div id="box">
this is box
div>
<br>
<div id="box1" *ngIf="flag">
this is box1
div>
<router-outlet>router-outlet>
app.component.ts
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, FormArray, FormControl } from '@angular/forms';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
msg = "码上加油站"
public flag: boolean = true;
constructor() {
};
ngOnInit(): void {
//组件和指令初始化完成 并不是真正的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";
}
}
效果:
执行css的动画示例
app.component.html
<div >
<h1>
{{ msg }}
h1>
<div ><button (click)="showAnim()">执行动画button>div>
<div id="div1" class="div1">div>
div>
<router-outlet>router-outlet>
app.component.ts
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, FormArray, FormControl } from '@angular/forms';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
msg = "码上加油站"
public flag: boolean = true;
constructor() {
};
ngOnInit(): void {
}
ngAfterViewInit() {
}
showAnim() {
//原生js获取dom节点
console.log('showAnim')
let oDiv: any = document.getElementById('div1');
oDiv.style.transform = "translate(100%,0)";
}
}
app.component.scss
.div1 {
width: 100px;
height: 100px;
background: red;
left: 50px;
top: 50px;
}
效果:
完
码上加油站
一起来加油
长按扫码关注
![cab7043a24bc8cafe245f5f361bc71ed.png](https://i-blog.csdnimg.cn/blog_migrate/f30134556f8a91da3d1cc684fecec07b.jpeg)