如何通過ngOnInit將圖片添加到背景中? 我不想在CSS中使用background: url("link of my image")
,因爲這會增加我網站的負載。我想通過角2打字稿做到這一點Angular 2中的背景圖片
1
A
回答
1
你覺得沒錯!它可以通過很多方式完成!
1)通過改變風格輸入:
import {Component} from '@angular/core'
import { DomSanitizer } from '@angular/platform-browser';
@Component({
selector: 'my-app',
template: `
<div>
<div [style]="getStyle()">
I am a div that wants to be styled
</div>
<button (click)="showStyle = !showStyle;">Toggle style</button>
</div>
`
})
export class App {
showStyle: false;
constructor() {
}
getStyle() {
// snip snip -> fetch the url from somewhere
const profilePicUrl = 'some-remote-server-url.jpg';
const style = `background-image: url(${profilePicUrl})`;
// sanitize the style expression
return this.sanitizer.bypassSecurityTrustStyle(style);
}
}
2)通過改變ngClass:
而且在ngOnInit()設置要
3的可變)加入指令:
import {Directive, ElementRef, Renderer} from '@angular/core';
@Directive({
selector: '[setBackgroundImage]',
})
export class StyledDirective {
constructor(public el: ElementRef, public renderer: Renderer) {
// el.nativeElement.style.backgroundColor = 'yellow';
renderer.setElementStyle(el.nativeElement, 'backgroundImage', 'yourImageLink');
}
}
還有很多ot她在這個來源的方式,例如: https://juristr.com/blog/2016/01/learning-ng2-dynamic-styles/
1
在你component.ts,進口DomSanitizer
,
進口{} DomSanitizer從「@角/平臺的瀏覽器;
... delare在你的組件類的變量,說backgroundImageStyle
和初始化ngOnInit
這個變量:
backgroundImageStyle: string;
constructor(private sanitizer: DomSanitizer) { }
public ngOnInit()
{
this.backgroundImageStyle = this.getBackgroundImageStyle();
}
private getBackgroundImageStyle()
{
let backgroundImage = './path/to/your/image';
// sanitize the style expression
const style = `background-image: url(${backgroundImage})`;
return this.sanitizer.bypassSecurityTrustStyle(style);
}
,並在組件的HTML,設置您的主要容器的樣式屬性:
[style]="backgroundImageStyle"
相關問題
- 1. Angular 2 - 預加載背景圖片?
- 2. Angular 2背景圖像webpack 2
- 3. html toggle 2背景圖片
- 4. 如何在Angular 2組件中添加背景圖片?
- 5. MySQL/PHP的背景圖片URL 2
- 6. 帶2張圖片的HTML背景
- 7. 背景圖片上的背景圖像
- 8. 背景圖片
- 9. 背景圖片
- 10. 背景圖片
- 11. CSS中的背景圖片
- 12. JToolBar中的背景圖片
- 13. JFrame中的背景圖片
- 14. div中的背景圖片
- 15. HTML 2顏色背景+重複圖片?
- 16. 居中CSS背景圖片
- 17. 居中背景圖片?
- 18. Jumbotron背景圖片
- 19. QLineEdit背景圖片
- 20. JOptionPane背景圖片
- 21. UIProgressView背景圖片
- 22. 多背景圖片
- 23. JPanel背景圖片
- 24. Bootstrap背景圖片
- 25. UITableViewController背景圖片
- 26. AndEngine背景圖片
- 27. Joomla背景圖片?
- 28. 背景CSS圖片
- 29. Android背景圖片
- 30. Android:背景圖片
據我所知在css中完成的樣式更快,然後在js中完成。 – onetwo12
真的嗎? 我的着陸載入所有內容,之後我看到圖像和登錄表單。我需要加載登錄表單,並在同一時間加載圖像 –