在切换 Angular 之前,我在
javascript
工作。我想更改打字稿中某些元素的 css
属性值。但我发现你不能像javascript
那样改变它:name.style.color='red'
。
与
javascript
我会写:
HTML:
<div id="blue" style="background-color:red;">
Hello
</div>
<button id="it">Press</button>
JS:
let blue=document.getElementById("blue");
let it=document.getElementById("it");
it.onclick= ()=> blue.style.backgroundColor="blue";
但在打字稿中它不起作用: HTML:
<div id="blue" style="background-color:red;">
Hello
</div>
<button (click)="switch()">Press</button>
TS:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'my_app_2';
blue=document.getElementById("blue");
switch() {
this.blue.style.backgroundColor="blue";
}
}
我找到了一个灵魂,但我想知道是否有更“自然”的方式来做到这一点,就像在 JavaScript 中一样。该解决方案的代码如下: HTML:
<div id="blue" [ngStyle]="this.clicked==true?{'background-color':'blue'}:{'background-color':'red'}">
Hello
</div>
<button (click)="switch()">Press</button>
TS:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'my_app_2';
clicked=false;
switch() {
this.clicked=!this.clicked;
}
}
使用
Renderer2
的功能setStyle
。
在 Angular 中,避免使用
document
,而应该使用 @ViewChild
。
示例:
<!-- your-component.html -->
<div #blue></div>
// your-component.ts
export class MyComponent {
@ViewChild('blue') blue: ElementRef;
// Inject Renderer2 in your constructor
constructor(private renderer: Renderer2) { }
// Use it in your function
switch () {
this.renderer.setStyle(this.blue.nativeElement, 'background-color', 'blue');
}
}
您可以在将值设置为函数或属性时使用
ngClass
在控制器中:
import { Component } from '@angular/core';
@Component({
// ...
})
export class AppComponent {
clicked = false;
switch() {
this.clicked = !this.clicked;
}
getBackgroundColor(): string {
if (this.clicked) {
return 'blue';
}
return 'red';
}
}
在模板中:
<div id="blue" [ngStyle]="{'background-color': getBackgroundColor()}">
Hello
</div>
<button (click)="switch()">Press</button>