可拖拽元素
其中,.parent是边界元素的类名。 2. 在父组件的component.ts文件中,使用ViewChild获取边界元素。 例如:
import { Component, ViewChild, ElementRef } from '@angular/core';
@Component({
selector: 'app-parent',
template: `
可拖拽元素
`,
styles: [`
.parent {
height: 300px;
width: 300px;
border: 1px solid #ccc;
overflow: auto;
}
`]
})
export class ParentComponent {
@ViewChild('parent', {static: true}) parentElRef: ElementRef;
}
在上面的示例中,我们使用ViewChild获取了父组件模板中的div元素,从而作为边界元素进行了限制。注意,在获取元素时必须设置static为true,因为ViewChild默认是在ngAfterViewInit周期中才会更新。 3. 在父组件的 ngOnInit() 生命周期钩子中,使用Renderer2为可拖拽元素设置边界限制。 例如:
import { Component, ViewChild, ElementRef, Renderer2 } from '@angular/core';
@Component({
selector: 'app-parent',
template: `
可拖拽元素
`,
styles: [`
.parent {
height: 300px;
width: 300px;
border: 1px solid #ccc;
overflow: auto;
}
`]
})
export class ParentComponent {
@ViewChild('parent', {static: true}) parentElRef: ElementRef;
@ViewChild('dragElem', {static: true}) dragElemRef: ElementRef;
constructor(private renderer: Renderer2) {}
ngOnInit() {
const parentEl = this.parentElRef.nativeElement;
const dragElem = this.dragElemRef.nativeElement;
this.renderer.setStyle(dragElem, 'max-height', `${parentEl.offsetHeight}px`);
this.renderer.setStyle(dragElem, 'max-width', `${parentEl.offsetWidth}px`);
}
}
在上面的示例中,我们使用Renderer2为可拖拽元素设置了边界限制,即设置其最大高度和宽度不能超过父元素对应的高度和宽度。