gpt4 book ai didi

html - 绑定(bind)到主机的 css 属性(而不是类)

转载 作者:太空狗 更新时间:2023-10-29 18:32:24 24 4
gpt4 key购买 nike

我如何获得 css 属性而不是 Angular2 中的类?

我有以下代码:

应用程序组件.ts:

import { Component, HostBinding } from '@angular/core';

@Component({
selector: 'body',
templateUrl: 'views/masterpage.html'
})
export class AppComponent {
@HostBinding('attr.class') hostClass = "sticky-header sidebar-open"; // Works, but not what i want
@HostBinding('style.position') hostPosition:string; // Does not work

sidebarToggle() {
this.sidebarCollapsed = !this.sidebarCollapsed;
this.hostClass = (this.sidebarCollapsed ? "sidebar-collapsed" : "sticky-header sidebar-open");

// Here I wanna check what is the 'position' property of my host (body).
// See "style-responsive.css"
}
}

样式响应.css:

@media screen and (max-width: 1024px) {
body {
position: relative;
}
}

因此,如您所见,只要用户缩小窗口,页面就会添加相对于正文的位置。

我只想在我的 Angular 组件中获取这些信息。如果窗口大于 1024px,hostPosition 应该是未定义的,如果小于 1024px,则应该是 'relative'。

如何实现?

最佳答案

@HostBinding() 不适合阅读,只适合写作。

你可以使用

@HostBinding('style.position') hostPosition:string;

获取分配给元素style.positionhostPosition值,但读取当前style.posotion

constructor(private elRef:ElementRef) {
console.log(elRef.nativeElement.offsetLeft);
console.log(elRef.nativeElement.offsetTop);
}

关于html - 绑定(bind)到主机的 css 属性(而不是类),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41017448/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com