想要操纵样式的显示。这是模板:
<div style="display: none" #myDiv />
有两种方法可以做到:
-
直接
if (1===1) this.myDiv.style.display = "block";
-
通过@ViewChild
@ViewChild('myDiv',{ static: false}) myDiv if (1===1) this.myDiv.style.display = "block";
没有工作。
想要操纵样式的显示。这是模板:
<div style="display: none" #myDiv />
有两种方法可以做到:
直接
if (1===1) this.myDiv.style.display = "block";
通过@ViewChild
@ViewChild('myDiv',{ static: false}) myDiv
if (1===1) this.myDiv.style.display = "block";
没有工作。
您可以如下使用ElementRef
。
HTML
<div class="my-div" style="display: none" />
TS
export class MyComponent implements AfterViewInit {
myDiv;
constructor(private elementRef:ElementRef) {}
ngAfterViewInit() {
this.myDiv = this.elementRef.nativeElement.querySelector('.my-div');
}
}
然后,您可以使用myDiv
变量来更改样式,如下所示。
this.myDiv.style.display = 'block';
,
使用ngStyle
:
<div [ngStyle]="{'display': flag ? 'block' : 'none'}">
...
</div>
其中flag
可以根据您在相应.ts文件中的逻辑对应于任何布尔变量。
您也可以使用Renderer2设置样式,setStyle的原型如下:
setStyle(el: any,style: string,value: any,flags?: RendererStyleFlags2): void
参数:
el: any,The element for whcih you set the style.
style: string,The name of the style.
value: any,The new value for style.
flags RendererStyleFlags2,Flags for style variations. No flags are set by default.
因此您必须避免使用ElementRef ,因为直接访问dom不利于安全,也不安全,您可以使用Renderer2设置Style
演示示例:
https://stackblitz.com/edit/renderer2-example-2-oryw2m?file=src/app/app.component.ts
代码示例:
import { Component,Renderer2,AfterViewInit,ViewChild,ElementRef } from '@angular/core';
@Component({
selector: 'my-app',templateUrl: './app.component.html',styleUrls: [ './app.component.css' ]
})
export class AppComponent implements AfterViewInit {
@ViewChild('test') test: ElementRef;
constructor(private renderer: Renderer2) {}
ngAfterViewInit() {
this.renderer.setStyle(this.test.nativeElement,'backgroundColor','red');
this.renderer.setStyle(this.test.nativeElement,'color','white');
}
}