简体   繁体   中英

How to conditionally add style attribute to template in angular?

I've seen examples of how to create a conditional style. However I do not want the style attribute to appear in some cases. This is what I want:

<div class="backgroundGradient" [style.backgroundImage]="myBackgroundImageUrl"></div>

However this issue here is when the myBackgroundImageUrl doesn't exist. I want backgroundGradient to show up. The problem here is angular will just display <div style="background-image: none"> . In chrome debugger if I remove this - my code works.

I basically don't want the style attribute to show up at all if myBackgroundImageUrl doesn't exist. Ternary doesn't work here either.

I want to know if its possible to do this without using 2 elements with *ngIf. That is worst case scenario but by element has a ton more attributes so I'm trying to avoid replicating unnecessarily.

What about

<div class="backgroundGradient" [ngStyle]="myStyle"></div>

componenet.ts

myStyle:any

ngOnInit() {
  if (hasImage) {
  this.myStyle={'background-image':url}
  }

https://angular.io/api/common/NgStyle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM