【问题标题】:Can't set a background image (with gradient) in Angular 9无法在 Angular 9 中设置背景图像(带渐变)
【发布时间】:2020-05-01 00:11:41
【问题描述】:

正如标题所述,我似乎无法设置此背景图片。 我已经尝试了很多方法。目前我的代码中有这个:

export class HeroComponent implements OnInit {
  @Input() content: PageContent[];

  public backgroundImage: string;

  constructor() { }

  ngOnInit(): void {
    this.getComponent()
  }

  private getComponent(): void {
    this.content.forEach((component: PageContent) => {
      if (component.type !== 'hero') return;
      let url = component.fields.backgroundImage.fields.file.url;
      this.backgroundImage = `linear-gradient(to bottom, rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url('${url}');`;
      console.log(component.fields.backgroundImage.fields)
      console.log(this.backgroundImage);
    })
  }
}

console.log 返回:

linear-gradient(to bottom, rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url('//images.ctfassets.net/90y01jqko4hp/15dPFmnMsX64iOL15WJIVR/457c906c79652365ff749ea2d5d11856/默认-bg.jpg');

这是对的。 我的 html 正在尝试这样做:

<div class="jumbotron" [ngStyle]="{ 'background-image': backgroundImage }" *ngIf="backgroundImage">

元素已渲染,因此有背景图像,但它不起作用。 另外,我试过了:

<div class="jumbotron" [style.background]="backgroundImage" *ngIf="backgroundImage">

问题是,如果我像这样复制字符串并将其放入我的 css 中:

.jumbotron {
    background-image: linear-gradient(to bottom, rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url('//images.ctfassets.net/90y01jqko4hp/15dPFmnMsX64iOL15WJIVR/457c906c79652365ff749ea2d5d11856/default-bg.jpg');
}

没有任何问题。 有谁知道我做错了什么?

【问题讨论】:

    标签: angular ng-style


    【解决方案1】:

    我认为问题是;在字符串的末尾。 Demo

    这给出了结果

      backgroundImage="linear-gradient(to bottom, rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url('//images.ctfassets.net/90y01jqko4hp/15dPFmnMsX64iOL15WJIVR/457c906c79652365ff749ea2d5d11856/default-bg.jpg')" 
    

    但这不是

    backgroundImage="linear-gradient(to bottom, rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url('//images.ctfassets.net/90y01jqko4hp/15dPFmnMsX64iOL15WJIVR/457c906c79652365ff749ea2d5d11856/default-bg.jpg');"
    

    【讨论】:

      猜你喜欢
      • 2020-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-01
      • 2011-08-06
      • 2019-09-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多