如何使用 Angular 2 中的指令在主机元素上设置计算的宽度



我有一个名为resize的指令,它处理一些鼠标事件并计算鼠标移动时的width,它会发出指令的宽度。

我在组件内的div上使用此指令,例如small.组件small在使用它的父组件的位置。small组件的width设置为200px。现在,我想在small组件的主机元素上设置指令中正在计算的宽度。

这是代码:

small.component.html:

<div class="root">
<div>... some elements</div>
<div class="sizer" resize></div>
</div>

small.component.ts:

import { Component, OnChanges, OnInit, EventEmitter, Input, Output } from "@angular/core";
@Component({
selector: "comp-small",
providers: [SmallService],
templateUrl: "./small.component.html",
})
export class Small implements OnInit {
constructor() {
}
// some functionality
}

小.scss:

comp-small {
width: 200px;
}

parent.component.html:

<comp-small></comp-small>
<div class="blah"></div>

指令调整大小:

import { Directive, Output, EventEmitter, ElementRef, HostListener, Input } from "@angular/core";
@Directive({
selector: "[resize]"
})
export class Resize {
private stPoint: number;
private endPoint: number;
private root: HTMLElement;
private width: number;
@Output() resizer = new EventEmitter();
constructor(private _el: ElementRef) {
this.root = this._el.nativeElement;
console.log("Root Element", this.root);
}
@HostListener('mousedown', ['$event'])
private _onMouseDown(event) {
this.stPoint = event.pageX;
console.log("Starting pt", this.stPoint);
}
@HostListener('mousemove', ['$event'])
private _onMouseMove(event) {
if (this.stPoint) {
if (event.type === "mousemove") {
this._endPoint = event.pageX;
console.log("end pt: mousemove", this.endPoint);
} 
this.width = this.endPoint - this.stPoint;
console.log("This Width", this.width);
this.resizer.emit(this.width);
}
}
@HostListener('mouseup', ['$event'])
private _onMouseUp(event) {
console.log("Width", this.width);
}
}

如何使用指令中计算的宽度设置comp-small的宽度。任何帮助将不胜感激。

谢谢。

我不确定我是否正确理解它。但是,如果要向具有此模板的组件发出宽度:

<div class="root">
<div>... some elements</div>
<div class="sizer" resize></div>
</div>

然后像这样做:

<div class="root">
<div>... some elements</div>
<div class="sizer" resize (resizer)="onResize($event)"></div>
</div>

在small.component.ts中,像这样:

constructor(
private renderer: Renderer2,
private elementRef: ElementRef,
) {}
onResize(width) {
this.renderer.setStyle(this.elementRef.nativeElement, 'width', `${width}px`);
}

最新更新