第一次接触angular项目,此文档为摸索学习过程中的记录文档,所有内容均不保证正确,不要随便相信,如有更优解,请在评论中给出,多谢。
有时间将不断更新。
第一天
@ViewChild获取不到nativeElement属性
出现问题:
ERROR TypeError: Cannot read properties of undefined (reading ‘nativeElement’)
<div #testdom>测试dom</div>
export class TestClass implements OnInit {
@ViewChild('testdom') testdom: ElementRef;
// 属性和指令初始化完成调用
ngOnInit() {
this.testFun();
}
testFun() {
console.log(this.testdom); // undefined
}
};
问题原因:
ngOnInit() 生命周期内只是初始化了组件,并不能获取到真实的 dom。
解决方法:
- 使用定时器setTimeout:
testFun() {
setTimeout(function () {
console.log(this.testdom); // 此时可获取到nativeElement属性
}, 0)
}
- 在ngAfterViewInit()中调用:
export class TestClass implements OnInit, AfterViewInit {
@ViewChild('testdom') testdom: ElementRef;
// 属性和指令初始化完成调用
ngOnInit() {
}
// 属性和指令初始化完成调用
ngAfterViewInit() {
this.testFun();
}
testFun() {
console.log(this.testdom); // 此时可获取到nativeElement属性
}
};
知识点:
总结:
- ngOnChanges( )当数据绑定输入属性的值发生变化时候调用;
- ngOnInit( )在第一次ngOnChanges( )后调用;说明这两个方法一般是配合工作的;
- ngOnInit( )用于Angular获取输入属性后初始化组件,此方法是钩子方法,在ngOnChanges( )方法被调用之后使用;
- ngOnInit( )钩子只会被调用一次;
- ngAfterViewInit( )钩子在初始化完组件视图及其子视图之后调用;
扩展使用:
结合echarts图标绘制:
<div #myEcharts style="width: 400px; height: 200px"></div>
import * as echarts from 'echarts';
export class TestClass implements OnInit, AfterViewInit {
@ViewChild('myEcharts') myEcharts: ElementRef;
// 属性和指令初始化完成调用
ngAfterViewInit() {
this.setCharts();
}
// 配置echarts属性
setCharts(obj = {}) {
opt = {
tooltip: {
trigger: 'axis'
},
xAxis: {
type: 'category',
data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
},
yAxis: {
type: 'value',
},
series: [
{
name: '浏览量',
type: 'line',
data: [120, 200, 150, 80, 70, 110, 130],
},
]
};
let dom = this.myEcharts.nativeElement;
return echarts.init(dom).setOption(opt, true);
}
};
第二天
出现问题:
ERROR Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'ngForOf: '…
<ul>
<li *ngFor="let item of arr">{{item.name}}</li>
</ul>
import * as echarts from 'echarts';
export class TestClass implements OnInit, AfterViewInit {
arr = [];
// 属性和指令初始化完成调用
ngAfterViewInit() {
this.arr = [{ name: 'AA' }];
}
};
问题原因:
dom渲染到这里时,arr里还没有元素,name此时为undefined。
解决方法:
先获取数据,再往dom上渲染。
import * as echarts from 'echarts';
export class TestClass implements OnInit, AfterViewInit {
arr = [];
// 属性和指令初始化完成调用
ngOnInit() {
this.arr = [{ name: 'AA' }];
}
};