Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/css/35.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何通过typescript更新CSS_Css_Angular_Typescript - Fatal编程技术网

如何通过typescript更新CSS

如何通过typescript更新CSS,css,angular,typescript,Css,Angular,Typescript,我有一个默认情况下隐藏的饼图: .sub-chart { min-height: 300px; width: 100%; margin-bottom: 24px; visibility: hidden; } 但是,当用户在不同的图表上进行筛选时,我想更改css可见性属性,以便图表不再隐藏 如何通过typescript组件文件更新css?创建属性 isDivVisible="visible" 在html中,give作为其样式 <div class="s

我有一个默认情况下隐藏的饼图:

 .sub-chart {
    min-height: 300px;
    width: 100%;
    margin-bottom: 24px;
    visibility: hidden;
 }
但是,当用户在不同的图表上进行筛选时,我想更改css可见性属性,以便图表不再隐藏

如何通过typescript组件文件更新css?

创建属性

isDivVisible="visible"
在html中,give作为其样式

<div class="sub-chart" [style.visibility]="isDivVisible"></div>

您可以使用
ViewChild
decorator和
Renderer2
服务来完成此操作,如下所示:

1) 在组件模板中,添加模板变量:

<my-element #myElement></my-element>

2) 在ts文件中:

@ViewChild('myElement') myElement: ElementRef<any> // the argument type can be HTMLElement / HTMLDivElement / component etc.

constructor(private renderer: Renderer2) {}

myMethod() {
 this.renderer.setStyle(this.myElement.nativeElement, 'visibility', 'visible');
}
@ViewChild('myElement')myElement:ElementRef//参数类型可以是HTMLElement/htmlVelment/component等。
构造函数(私有呈现器:Renderer2){}
myMethod(){
this.renderer.setStyle(this.myElement.nativeElement,'visibility','visible');
}
必须从
@angular/core
导入ViewChild、Renderr2、ElementRef

您还可以使用
addClass
和/或
removeClass
方法代替
setStyle
用于渲染器

如果使用Angular 8,则需要将配置对象作为第二个参数传递给@ViewChild,如下所示:
@ViewChild('myElement',{static:false})
。如果在OnInit生命周期挂钩中使用
static
属性,则必须将其设置为
true
(同样适用于Angular 9)


您可以使用
`并使条件为真/假。由于样式优先于类,所以您可以看到“div”的效果,但可以说,最好是将css类交换进来和交换出去,而不是直接在代码中调整样式。您可以绑定到[ngClass]来执行此操作。看见
@ViewChild('myElement') myElement: ElementRef<any> // the argument type can be HTMLElement / HTMLDivElement / component etc.

constructor(private renderer: Renderer2) {}

myMethod() {
 this.renderer.setStyle(this.myElement.nativeElement, 'visibility', 'visible');
}