Guide on showing a placeholder image in Angular2 when the image is missing

I am trying to figure out how to display a default image when the image source coming from the backend is null. Can someone assist me with this issue? If the image part is null, then I want to display the following image:

"../assets/images/msg.png"

Console: https://i.sstatic.net/C1AQb.png

HTML:

<ul>
    <li *ngFor="let message of activeMessages" (click)="showMessage(message)" [class.activeShow]="message.id == message_id">
        <span>{{message.updated_at  | date:'dd.MM.yyyy'}}</span>
        <img src="{{message.from_user_image}}" alt="img"/>  
    </li>
</ul>
<ul>
    <li *ngFor="let reply of message_show.messages">
        <img src="{{reply.from_user_image}}"/>
        <p><b>{{reply.name}} </b> <span> {{reply.updated_at | date:'dd.MM.yyyy'}} - {{reply.updated_at | date:'h:mm'}}</span></p>
        <p>{{reply.text}}</p>
    </li>
</ul>

Ts:

loadMessages() {
    this.service.getMessages().subscribe(
        data => {
            this.messagesdata = data;
            this.activeMessages = data.filter(msg => msg.active == true);
            this.closedMessages = data.filter(msg => msg.active == false);
            
            if (this.activeMessages.length > 0) {
                if(!this.message_show) {
                    var test = this.message_show = this.activeMessages[0];
                    this.message = true;
                    this.message_id = this.activeMessages[0].id;
                    
                    this.message_show.messages.map(function(msg) {
                        if(msg.from_user_id == test.from_user_id) {
                            msg.from_user_image = test.from_user_image;
                        } else {
                            msg.from_user_image = test.to_user_image;
                        }
                        
                        if(msg.to_user_id == test.to_user_id) {
                            msg.to_user_image = test.to_user_image;
                        } else {
                            msg.to_user_image = test.to_user_image;
                        }
                    })
                }
            }
            
            if (this.closedMessages.length > 0) {
                if(!this.message_close) {
                    var test2 = this.message_close = this.closedMessages[0];
                    this.message_idc = this.closedMessages[0].id;
                    
                    this.message_close.messages.map(function(msg) {
                        if(msg.from_user_id == test2.from_user_id) {
                            msg.from_user_image = test2.from_user_image;
                        } else {
                            msg.from_user_image = test2.to_user_image;
                        }
                        
                        if(msg.to_user_id == test2.to_user_id) {
                            msg.to_user_image = test2.to_user_image;
                        } else {
                            msg.to_user_image = test2.to_user_image;
                        }
                    })
                }
            }              
        },
        error => {}
    );
}

Answer №1

Understanding your code may be a bit challenging, but the key idea is to do the following (utilize the reply.from_user_image unless it's null, in which case use '../assets/images/msg.png'):

<img [src]="reply.from_user_image || '../assets/images/msg.png'"/>

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

ControlValueAccessor can automatically detect when the required property is enabled on a reactive form

Is there a way to detect within a custom control, that implements ControlValueAccessor and is exclusively utilized with reactive forms, when the required validator has been added or removed? I am looking for an alternative solution instead of creating an ...

What happens when arithmetic operators are applied to infinity values in JavaScript?

Why do Arithmetic Operators Behave Differently with Infinity in JavaScript? console.log(1.7976931348623157E+10308 + 1.7976931348623157E+10308)//Infinity console.log(1.7976931348623157E+10308 * 1.7976931348623157E+10308)//Infinity console.log(1.797693134 ...

Aligning form elements horizontally with Angular 2 Material

Thank you in advance for taking the time to assist me. Your help means a lot! I have developed a form using Angular 2 Material Design and I am facing an issue with aligning two elements. Specifically, how can I align Bill Number and Year as shown in the s ...

typescript in conjunction with nested destructuring

ES6 has definitely made coding more efficient by reducing the number of lines, but relying solely on typescript for everything may not be the best approach. If I were to implement type checking for arguments that have been destructed multiple levels deep, ...

Can multiple Observables be used to display FormArray data within a FormGroup effectively?

I've spent countless days attempting to asynchronously display dynamically loaded FormArray data without success. Essentially, I have a FormGroup that is created on click and shown in a modal window (no issues with displaying data loaded in the subscr ...

Is it possible to create a ASP.NET 5 (Core) Website using TypeScript and Node (or ESM) modules within Visual Studio 2019, excluding Visual Studio Code?

After following a helpful guide on setting up TypeScript in an ASP.NET 5 website project using Razor Pages, I decided to enhance my typings with Node modules instead of just importing as 'any'. My goal was to integrate a Node module like EthersJ ...

Using TypeScript to eliminate duplicate values when constructing an array with various properties

Recently, I received an array from an API that has the following structure: results = [ {name: 'Ana', country: 'US', language: 'EN'}, {name: 'Paul', country: 'UK', language: 'EN'}, {name: & ...

A single network request is made for every subscription

When making a post request using HTTPClient and subscribing to the returned observable, I am encountering strange behavior where each subscription triggers a new post request. So, if I subscribe to the observable 5 times, I end up with 5 separate post requ ...

Angular configuration files fail to be exchanged promptly

I am utilizing Angular 9 with the View Engine compiler. I have two separate files where I hold environment variables: environment.ts: export const environment: any = { production: false, }; environment.prod.ts: export const environment: any = { ...

The Angular Karma tests are failing because the custom tag is not recognized as a known element

I've recently started learning Angular and encountered an issue with my first Karma test. The error message I received is as follows: AppComponent should create component Error: Template parse errors: 'ereturn-form' is not a known element: ...

Exploring Angular2's DOMContentLoaded Event and Lifecycle Hook

Currently, I am utilizing Angular 2 (TS) and in need of some assistance: constructor(public element:ElementRef){} ngOnInit(){ this.DOMready() } DOMready() { if (this.element) { let testPosition = this.elemen ...

Angular 2 - Utilizing `return` in the `then` method for async operations

Currently, I am facing a scenario where it would be very useful if there was a way to retrieve the value obtained in the .then() function. Allow me to explain why and what exactly I need. For almost every API call, I need to include the API_KEY and DEVIC ...

Create a hierarchical tree structure using a string separated by dots

I am struggling with organizing a tree structure. :( My goal is to create a tree structure based on the interface below. export type Tree = Array<TreeNode>; export interface TreeNode { label: string; type: 'folder' | 'file'; ...

After restoring my Windows system, I encountered an issue with locating the typescript.js module for my Angular app development. I am currently troubleshooting the build

My PC had some issues, so I decided to restore Windows to an older restoration point. However, after doing this, I encountered an error while trying to build my Angular App: C:\Udemy\AngularDeCeroAExpertoEdicion2021\03-paisesApp>npm run ...

Angular developers are struggling to find a suitable alternative for the deprecated "enter" function in the drag and drop CDK with versions 10 and above

By mistake, I was working on an older version of Angular in StackBlitz (a code-pane platform). I came across a function called enter on GitHub, but it didn't solve my issue. I was working on a grid-based drag and drop feature that allows dragging bet ...

TS2304 TypeScript (TS) Unable to locate the specified name

Encountering an error message stating Cannot find name 'Record'. Do I need to install a specific package for this class? Severity Code Description File Project Line Suppression State Error TS2304 (TS) Cannot find name 'Record ...

There is no corresponding index signature for type 'string' in Type

This is the code snippet I am using as a reference: const MyArray = [ { name: "Alice", age: 15 }, { name: "Bob", age: 23 }, { name: "Eve", age: 38 }, ]; type Name = typeof MyArray[string]["name"]; //throws err ...

Tips for organizing JSON data from a multiselect form

I am currently working on a template driven form with a multiselect field named assets. My framework of choice is semantic UI. <div ngModelGroup="assets"> <div class="field"> <label for="resourceName">Assets</label ...

Issue with building Webpack React Router DOM configuration

I recently developed a React+Typescript app with Webpack 5 configuration completely from scratch. Everything was running smoothly in development mode, and I utilized React Router DOM version 6.23.1 for routing. However, once I built the app, some component ...

Multiple invocations of the callback function in an Angular5 template binding

In trying to create a grid component that uses structured data containing definitions for columns and an array of data. Each column definition includes a callback function to customize the display of that specific column's value. Within each callbac ...