We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
<div class='old-style'></div>
.old-style{ width: 100px; height: 100px; background: #000; }
我想给它改变它的样式为
.new-style{ width: 200px; background: #069; }
获得DOM元素的引用移除旧的class old-style添加class new-style
old-style
new-style
<div class='old-style' #demo></div>
import { Component, ElementRef, ViewChild, Renderer2 } from '@angular/core'; ... export class DemoComponent implements OnInit { constructor( private renderer2 : Renderer2) { } @ViewChild('demo') demo: ElementRef; ngOnInit(){ this.renderer2.removeClass(this.demo.nativeElement, "old-style"); this.renderer2.addClass(this.demo.nativeElement, "new-style"); } }
获得DOM元素的引用设置新的 style
import { Component, ElementRef, ViewChild, Renderer2 } from '@angular/core'; ... export class DemoComponent implements OnInit { constructor( private renderer2 : Renderer2) { } @ViewChild('demo') demo: ElementRef; ngOnInit(){ this.renderer2.setAttribute(this.demo.nativeElement, "style","width: 200px;background: #006699;"); } }
这里是修改多个style所以用setAttribute,如果是修改单个style则使用 this.renderer2.setStyle(ele,name,value)
定义一个布尔值,通过布尔值的改变来改变其class
ts:
private changeClass : boolean = false; // 想要更改样式时直接更改 changeClass的值。
<div [ngClass]="changeClass ? 'new-class' : 'old-class' "></div>
当changeClass为false时 div class为old-class 为true时calss为 new-class
定义两个变量,通过变量改变来改变其style
private widthTemp : string = "100px"; private backgroundTemp : string = '#000'; // 想要更改样式时直接更改 changeClass的值。 this.widthTemp = '200px;'; this.backgroundTemp = '#069'
html
<div [ngStyle]="{'background-color':backgroundTemp,'width': widthTemp}">></div>
The text was updated successfully, but these errors were encountered:
No branches or pull requests
需求: 有一个div,我要给他动态删除和增加样式
我想给它改变它的样式为
法一: 操作DOM,删除和增加class达到效果
法二: 操作DOM,修改其样式达到效果
法三: 不操作DOM使用 ngClass修改class
ts:
当changeClass为false时 div class为old-class 为true时calss为 new-class
法四: 不操作DOM使用 ngStyle修改style
ts:
html
The text was updated successfully, but these errors were encountered: