Using style binding and ngStyle doesn't appear to be effective for setting a background image within a DIV element in Angular5

After facing difficulties in customizing the spacing of Angular material cards, I decided to create my own cards. However, during this process, I encountered an issue where I needed to set an image as a background inside a div.

Despite trying various CSS styles, I couldn't achieve the desired result. For instance, when attempting to set the background image using the following code:

<div *ngIf="imgSrc" [style.background-image]="imgSrc" [style.background-size]="cover"></div>

Although this code did not throw any errors, the image was still not displaying within the div.

I also tried using ngStyle, but encountered an error when trying:

<div *ngIf="imgSrc" [ngStyle]="{
    'background-image': 'url(\'https://material.angular.io/assets/img/examples/shiba1.jpg\')'
  }"></div>

Error: Template parse errors:
Parser Error: Unexpected token Lexer Error: Unterminated quote at column 43 in expression [{
    'background-image': 'url(\'https:] at column 44 in [{
    'background-image': 'url(\'https://material.angular.io/assets/img/examples/shiba1.jpg\')'
  }] in ng:///AppModule/HomeCardComponent.html@37:26

I prefer setting the image through imgSrc rather than using a URL directly, but I am unsure how to accomplish this with ngStyle without encountering interpolation errors.

https://i.sstatic.net/TUbmv.png

Here is the HTML code snippet:

<div class="card shadow">
  <div class="row">
    <div class="col-md-7 card-body">
      <div class="card-domain">{{ domain }}</div>
      <div class="card-title">{{ title }}</div>
      <div class="card-date">{{ date }}</div>
      <div class="card-content">{{ content }}</div>
    </div>
    <div class="col-md-5">
      <div *ngIf="imgSrc" [style.background-image]="imgSrc" [style.background-size]="cover"></div>
    </div>
  </div>      
</div>

home-card.component.ts

import { Component, OnInit, Input } from '@angular/core';

@Component({
  selector: 'app-home-card',
  templateUrl: './home-card.component.html',
  styleUrls: ['./home-card.component.css']
})
export class HomeCardComponent implements OnInit {

  @Input() domain: string;
  @Input() title: string;
  @Input() date: string;
  @Input() content: string;
  @Input() imgSrc: string;

  constructor() { }

  ngOnInit() {
  }
}

home-card.component.css

.card{
height: auto;
max-width: 100%;
margin: 0px;
font-family: "Playfair Display", Georgia, "Times New Roman", serif;
}

home.component.ts

<div class="row">
    <div class="col-md-6">
        <div class="page-header">
            <h3>Latest Post</h3>
        </div>
        <app-home-card domain="XYZ" title="It should work!" date="Nov 12" content="Let's just assume it's working." imgSrc="https://material.angular.io/assets/img/examples/shiba2.jpg"></app-home-card>
    </div>
    <div class="col-md-6">
        <div class="page-header">
            <h3>Most Popular Post</h3>
        </div>
        <app-home-card domain="ABC" title="Why is it not working?" date="Nov 11" content="Or make it work somehow." imgSrc="https://material.angular.io/assets/img/examples/shiba2.jpg"></app-home-card>
    </div>
</div>

Answer №1

1. Make sure to double-check your URLs.
2. The code should look like this: 'url(' + imgSrc + ')'

<div class="card shadow">
  <div class="row">
    <div class="col-md-7 card-body">
      <div class="card-domain">{{ domain }}</div>
      <div class="card-title">{{ title }}</div>
      <div class="card-date">{{ date }}</div>
      <div class="card-content">{{ content }}</div>
    </div>
    <div class="col-md-5">
      <div *ngIf="imgSrc" [style.background-image]="'url(' + imgSrc + ')'" [style.background-size]="cover"></div>
    </div>
  </div>      
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Troubleshooting: AngularJS ng-repeat not rendering JSON data

I have successfully retrieved JSON data from a database using PDO in Angular. The data is being returned as expected when I encode it to JSON. However, I am facing an issue with displaying the data using ng-repeat in Angular. Although the div elements are ...

Issue with Typescript in react: JSX element lacks construct or call signatures

After upgrading TypeScript, I encountered the error mentioned above in one of my components. In that component's render method, I have the following code: render() { const Tag = props.link ? 'a' : 'div'; return ( < ...

Navigating in a Curved Path using Webkit Transition

Currently, I am working on a simple project to learn and then incorporate it into a larger project. I have a basic box that I want to move from one position to another using CSS webkit animations and the translate function for iOS hardware acceleration. I ...

Using JQuery to enable the movement of divs on a screen through clicking and dragging, without the use of

Recently, I've been experimenting with a small project involving draggable divs. However, the code I've written doesn't seem to be functioning properly, causing JQuery to become unresponsive. Is there an alternative method that is simple an ...

Making AngularJS work with angular-ui bootstrap and ensuring compatibility with IE8

Having trouble getting AngularJS code that utilizes angular-ui bootstrap to function properly in IE 8? Following the guidelines in the AngularJS developer guide on IE didn't seem to solve the issue for me. I inserted the code snippet below into my ind ...

Tips on how to highlight a clicked list item:

I'm currently attempting to access the key={1} Element within my li. My goal is to set the activeItem in State in order to compare it with the clicked item later on. If they are equivalent, I want to apply an active class to that specific element. How ...

What is the process for retrieving the value of a text box using V-Model?

Link to the code snippet <td><input class="input" v-model="user.name" /></td> After accessing the provided link, I noticed a unique input textbox. Is there a way to extract specific text values like a,b,c from this te ...

Sharing content on an Angular 4/5 webpage

I find myself in a situation where I am required to share a link to my web application with a client, and they will be submitting a form on my webpage. This application has been developed using Angular 5. Despite searching online for a solution, I have not ...

Is there a way to make the React component automatically refresh upon clicking the search button?

Just starting out with React and JavaScript, I decided to experiment with accessing a public API. Here is the function I created: import { useState } from "react"; import CountrySWR from "./CountrySWR"; export default function SearchFo ...

Toggle the display of slide numbers in RMarkdown xaringan / reveal.js presentations

In preparation for a workshop, I am creating HTML slides using the xaringan package in R, which is based on remark.js. These slides are made with RMarkdown, and while this approach has been effective, I have encountered a need to disable slide numbers on s ...

"Why does the function not work inside the template, but works when the logic is set inside the template

My logic was working perfectly -> for example: Everything was working fine until I tried to set my values inside ts and switch logic in ts.file component. But when I did it inside the ts file, it stopped working: It's not working anymore. Why i ...

Having trouble retrieving properties from a JavaScript JSON object?

I am currently working with a JSON object that contains properties for MAKEs, MODELs, YEARs, STATEs, PLATEs, and COLORs. There are 4 instances of each property within the object: Object {MAKE1="xxx ", MODEL1='xxx', YEAR1='xxx', STATE1= ...

Troubles encountered with example code: Nested class in an exported class - Integrating Auth0 with React and Node.js

I am currently attempting to execute tutorial code in order to create an authentication server within my React project. Below is the code snippet provided for me to run: // src/Auth/Auth.js const auth0 = require('auth0-js'); class Auth { co ...

tips for storing user input into an array

I am currently developing a calculator that uses Json data. The goal is to retrieve the Grid Code associated with a specific longitude and latitude input. However, I am encountering an issue where the result returned is 0, indicating that the value of the ...

The data received from the frontend is being replicated in the backend, causing duplication issues in a React

Whenever I click the button labeled onClick, it triggers the transmission of data (both time and ID) to the backend. The issue at hand is that the backend seems to be receiving the data twice instead of just once. On inspecting req.body, it becomes eviden ...

Vue not triggering computed property sets

As per the guidelines, I should be able to utilize computed properties as v-model in Vue by defining get/set methods. However, in my scenario, it isn't functioning as expected: export default{ template: ` <form class="add-upload&quo ...

What steps are needed to create a hover box that appears on the right side of my div?

I am attempting to customize the code found at this link so that the box slides to the left side instead of the right. I thought changing right: 0; to right: 100%; in the .overlay class would achieve this, but it is not working as expected. I want it to l ...

What is the best method for retrieving data from a specific collection in MongoDB?

Within the code snippet below, on the 4th line, 'Messages' is the name of my MongoDB collection that I created in another file. When I attempt to retrieve data from this collection, no errors occur. However, when I specify the name of a differen ...

Having trouble organizing the date strings in the material table column

In my Angular application, I have a material table with multiple columns that I am sorting using matSort. While I can successfully sort the last two columns in ascending or descending order, I am facing an issue with the first column which contains date va ...

How to Make Bootstrap 3 Collapse Panels Stand Out with an Active Class

First of all, here is the fiddle link: http://jsfiddle.net/krish7878/h38jn324 I have a simple question. When a panel is clicked and it expands to show its contents, a class 'active' should be added to 'panel-heading'. I came across a ...