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>