问题描述
在Angular 1中,所有DOM操作都应在指令中进行以确保适当的可测试性,但是Angular 2呢?这有什么变化?
In Angular 1 all DOM manipulation should be done in directives to ensure proper testability, but what about Angular 2? How has this changed?
我一直在寻找好的文章或关于DOM操作放置位置以及操作时的思考方式的所有信息,但是每次我都会空虚.
I've been searching for good articles or any information at all about where to put DOM manipulation and how to think when doing it, but I come up empty every time.
以该组件为例(这实际上是一条指令,但我们假装不是):
Take this component for example (this is really a directive but let's pretend that it's not):
export class MyComponent {
constructor(private _elementRef: ElementRef) {
this.setHeight();
window.addEventListener('resize', (e) => {
this.setHeight();
});
}
setHeight() {
this._elementRef.nativeElement.style.height = this.getHeight() + 'px';
}
getHeight() {
return window.innerHeight;
}
}
例如,事件绑定是否属于构造函数,还是应该将其置于ngAfterViewInit
函数或其他地方?您是否应该尝试将组件的DOM操作分解为指令?
Does event binding belong in a constructor for example, or should this be put in the ngAfterViewInit
function or somewhere else? Should you try to break out the DOM manipulation of a component into a directive?
目前还只是一片模糊,所以我不确定我是否正确处理了这个问题,而且我确定我不是唯一一个.
It's all just a blur at the moment so I'm not sure that I'm going about it correctly and I'm sure I'm not the only one.
Angular2中DOM操作的规则是什么?
What are the rules for DOM manipulation in Angular2?
推荐答案
在Angular2中应完全避免直接DOM操作.
Direct DOM manipulation should be avoided entirely in Angular2.
使用绑定,例如:
export class MyComponent {
constructor() {
this.setHeight();
}
@HostBinding('style.height.px')
height:number;
@HostListener('window:resize', ['$event'])
setHeight() {
this.height = window.innerHeight;
}
}
这篇关于DOM操作在Angular 2中属于什么地方?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!