牛魔王的故事
2022-10-27 14:51:59
我一直在 StackOverflow 和 Google 中尋找一段時間,但無法真正找到解決我的問題的方法。就這樣吧。我通過@ViewChildren('labelSquare') public labelIcon: QueryList<HTMLSpanElement>;裝飾器在 DOM 中有一組元素。在 HTML 中,我有以下內(nèi)容來綁定它: <span class="status-item" *ngFor="let status of statusList"> <div *ngIf="status.state !== 'Starting' && status.state !== 'Stopping' && status.state !== 'Synchronising' && status.state !== 'EmergencyStop'" > <div class="status"> <span #labelSquare class="status-square fas fa-square {{ status.state }}"></span> <span class="status-name">{{ status.text }}</span> </div> </div> </span>我從中得到了一個包含 58 個跨度元素的數(shù)組,現(xiàn)在想要附加一個比當(dāng)前背景顏色深 10% 的邊框。因此,我map為此使用了一個:if (this.labelIcon) { this.labelIcon.map((icon: HTMLSpanElement) => { const element = window.getComputedStyle(icon); icon.setAttribute('style', `border: 1px solid ${ColorUtil.darkenBorderFromBackground(element.color)}`); }); }我的ColorUtil.darkenBorderFromBackground()簡單回歸return darken(${backgroundColor}, 10%);(使用模板字符串,無法弄清楚如何在 StackOverflow 中格式化。我的問題是現(xiàn)在我得到了一個TypeError: Failed to execute 'getComputedStyle' on 'Window': parameter 1 is not of type 'Element'.誰能幫我嗎?
1 回答

幕布斯7119047
TA貢獻1794條經(jīng)驗 獲得超8個贊
Angular 返回一個ElementRef
非 DOM 元素。
ElementRef
有一個稱為nativeElement
DOM 元素的屬性。所以icon
改變icon.nativeElement
內(nèi)部window.getComputedStyle()
請注意,您的打字稿界面也需要在 map 方法內(nèi)進行更改。
例如
if (this.labelIcon) {
this.labelIcon.map((icon: ElementRef) => { // Not sure if ElementRef is a valid interface in Angular
const element = window.getComputedStyle(icon.nativeElement);
icon.setAttribute('style', `border: 1px solid ${ColorUtil.darkenBorderFromBackground(element.color)}`);
});
}
添加回答
舉報
0/150
提交
取消