我正在尝试创建一个将调整为所选项目宽度的选择。
以下是jQuery / Javascript中的实现:Drop down list width fit selected item text
我遇到的问题是样式总是空的。如果我尝试将mainSelectElement设置为hiddenSelectElement,它几乎会消失。原因是nativeElement.style.width是空白的。我将样式属性记录到控制台,每个属性都是空白的。我们还应用了全局样式进行选择,但这些样式也没有出现。
有谁知道为什么我的款式是空白的?这与shadow DOM有关吗?最重要的是,任何解决方案?
import { Component, Input, Output, EventEmitter, forwardRef, ViewChild, ElementRef, Renderer } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
const SELECT_RESIZE_VALUE_ACCESSOR: any = {
provide: NG_VALUE_ACCESSOR,
useClass: forwardRef(() => SamSelectResizableComponent),
multi: true
}
@Component({
selector: 'sam-select-resizable',
template: `
<select #mainSelectElement [ngModel]="selected" (ngModelChange)="updateSelected($event)">
<ng-content></ng-content>
</select>
<select #hiddenSelectElement>
<option >{{selected}}</option>
</select>
`,
providers: [
SELECT_RESIZE_VALUE_ACCESSOR
]
})
export class SamSelectResizableComponent implements ControlValueAccessor {
@ViewChild('hiddenSelectElement') hiddenSelectElement: ElementRef;
@ViewChild('mainSelectElement') mainSelectElement: ElementRef;
public selected: any;
private onChangeCallback: (_: any) => void = (_: any) => {};
private onTouchedCallback: () => void = () => {};
get value(): any {
return this.selected;
}
set value(val: any) {
if (val !== this.selected) {
this.selected = val;
this.onChangeCallback(this.selected);
}
}
constructor(private renderer: Renderer) {}
updateSelected(event) {
this.selected = event;
const hiddenWidth = this.hiddenSelectElement.nativeElement.style.width;
this.renderer.setElementStyle(this.mainSelectElement.nativeElement, 'width', hiddenWidth);
}
writeValue(value: any) {
if (value !== this.selected) {
this.selected = value;
this.onChangeCallback(this.selected);
}
}
registerOnChange(fn: any) {
this.onChangeCallback = fn;
}
registerOnTouched(fn: any) {
this.onTouchedCallback = fn;
}
}
答案 0 :(得分:4)
您应该直接从nativeElement
获取宽度,而不是从style
const hiddenWidth = this.hiddenSelectElement.nativeElement.clientWidth; //.width
答案 1 :(得分:1)
这是一种在应用样式后获取样式的好方法。最初,任何HTML元素的所有样式属性都是空的。
window.getComputedStyle()可能会解决您的问题。
// fetch styles for an element
style = window.getComputedStyle(hiddenSelectElement.nativeElement, null);
// fetch the property values for any style attribute
console.log(style.getPropertyValue("width"));
对于::before
和::after
// fetch styles for an element
style = window.getComputedStyle(hiddenSelectElement.nativeElement, ':before');
// fetch the property values for any style attribute
console.log(style.getPropertyValue("width"));
参考:https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle