display the picture depending on the circumstances

Is there a way for the image tag to display different images based on a condition?

I attempted the code below, but it's not displaying the image:

<img src="{{row.image}}!=null?'data:image/jpeg;base64,{{row.image}}':'./assets/img/quill1.png'">

Could someone please point out what mistake I might be making?

Answer №1

Learn how to selectively display elements with *ngIf

<img *ngIf="row.image" [attr.src]="'data:image/jpeg;base64,' + row.image" />
<img *ngIf="!row.image" src="./assets/img/quill1.png" />

Enhance:

It's advisable to construct the complete base64 src string in your typescript file

Enhance 2:

Illustration of conditional logic in attributes: https://stackblitz.com/edit/angular-cfbsid

This isn't my preferred method, just a demonstration

Answer №2

If you're looking to divide this into two separate elements, here's one way to do it:

<img *ngIf="row.image" [src]="'data:image/jpeg;base64,' + row.image" />
<img *ngIf="!row.image" src="./assets/img/quill1.png" />

Alternatively, you can connect the output to a get function in your .ts file:

html:

<img [src]="getImage"/>

ts:

get getImage() {
       return  this.row.image!=null?'data:image/jpeg;base64'+this.row.image:'./assets/img/quill1.png'
}

Answer №3

Give this a shot.

Occasionally, the browser may not support untrusted URLs, which is why it's recommended to utilize bypassSecurityTrustUrl for security purposes. More information can be found in the documentation https://angular.io/api/platform-browser/DomSanitizer

component.ts

import { DomSanitizer } from '@angular/platform-browser'; 

constructor(private xss: DomSanitizer) {}

safeURL(url: string): any {
    return this.xss.bypassSecurityTrustUrl(url);
}

component.html

<img [src]="row.image?safeURL('data:image/jpeg;base64,'+row.image):'/assets/img/quill1.png'"  alt="Avatar">   

Alternatively

<img [src]="safeURL('data:image/jpeg;base64,'+row.image)" onError="this.src='/assets/img/quill1.png'" alt="Avatar">   

Or

<img *ngIf="row.image; else noAvatar;" [src]="safeURL('data:image/jpeg;base64,'+row.image)" alt="Avatar"/> 
<ng-template #noAvatar>
  <img [src]="'./assets/img/quill1.png'" alt="No Avatar">
</ng-template>

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

Is there a possibility of Typescript expressions `A` existing where the concept of truthiness is not the same as when applying `!!A`?

When working with JavaScript, it is important to note that almost all expressions have a "truthiness" value. This means that if you use an expression in a statement that expects a boolean, it will be evaluated as a boolean equivalent. For example: let a = ...

Stop the pinch zoom functionality in Angular NativeScript WebView to prevent unwanted zooming

Currently, I am working on a Nativescript App that utilizes Angular (NG 5.1.1 / Angular 7.x). Within the app, there is a view containing a webview. @ViewChild("myWebView") webViewRef: ElementRef; <WebView class="webview" #myWebView [src]="myU ...

implementing an event listener in vanilla JavaScript with TypeScript

Can anyone help me figure out how to correctly type my event listener in TypeScript + Vanilla JS so that it has access to target.value? I tried using MouseEvent and HTMLButtonElement, but I haven't been successful. const Database = { createDataKeys ...

Using Rxjs to reset an observable with combineLatest

My scenario involves 4 different observables being combined using "combineLatest". I am looking for a way to reset the value of observable 2 if observables 1, 3, or 4 emit a value. Is this possible? Thank you! Mat-table sort change event (Sort class) Mat- ...

Challenges with Loading JSON Dynamically in Next.js using an NPM Package

In my TypeScript project, I have implemented a functionality where a json configuration file is dynamically loaded based on an enum value passed as a parameter to the getInstance function in my PlatformConfigurationFactory file. public static async getIn ...

Retrieve the value of a hidden input when a button is clicked using reactive forms in Angular

I am currently attempting to retrieve the values of hidden input fields that are dynamically added when the user clicks on the "insert more" button. If you'd like to view the code in action, you can visit this StackBlitz link: get hidden input value ...

Challenges with npm installation in Angular Quickstart

I've been following the Angular getting started guide and encountered some issues. After cloning the repository, I attempted to run npm install, but I'm encountering errors: npm WARN package.json <a href="/cdn-cgi/l/email-protection" class=" ...

Troubleshooting: ngModel in Angular 2 Component does not properly update the parent model

I have been attempting to develop a wrapper component for input elements like checkboxes, but I am facing an issue where the parent variable (inputValue) is not updating even though it has been defined as an ngModel. The code snippet for my component look ...

Tips for displaying the default keyboard with numbers and symbols on Ionic applications

Is there a way to display a keyboard like the image provided by default in an Ionic5 app for Android? I attempted using type="number", but it restricts input to numbers only. However, on iOS, the full keyboard is displayed with this type. When I ...

Construct an outdated angular project from scratch

I'm facing an issue with an old Angular project that I'm trying to build. After pulling down the code, running npm install @angular/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fc9f9095bccdd2cbd2c8">[email p ...

Create a pinia state by defining it through an interface without the need to manually list out each property

Exploring the implementation of state management (pinia) within a single-page application is my current task. We are utilizing typescript, and I am inquiring about whether there exists a method to define a state based on an interface without needing to ret ...

Utilize ngModelGroup to avoid duplicating the div element

Here is an example of a form layout: <input type="checkbox"> <input type="text"><br> <input type="checkbox"> <input type="text"><br> <input type="checkbox"> <input type="text"> All text fields belong to t ...

Choose the appropriate data type for the class variable (for example, fArr = Uint32Array)

const functionArray: Function = Uint32Array; new fArr(5); The code snippet above is functioning properly. However, TypeScript is throwing a TS2351 error: "This expression is not constructable. Type 'Function' has no construct signatures". I wo ...

The HttpEvent containing Observable of State arrays is not compatible with the type Observable of State arrays

My Angular app fetches state information from a REST API and showcases it on the website. In my state component, I invoke the state service, which in turn communicates with the backend using the httpClient.get() method. When passing parameters from the com ...

Can the script be loaded into a TypeScript file?

I'm currently in the process of integrating this script tag into my Angular 2 project, but I'm searching for a way to incorporate it into the typescript file so that I can access its methods within the .ts file. <script type="text/javascript" ...

Simple Steps to View Angular Logs in Terminal

Upon initializing my Angular project, I utilized the npm start command to kickstart the application. The console.log() function displays logs exclusively in the browser console window. Is there a way to view these logs in the terminal window? ...

Ensure the inferred type is asserted in TypeScript

Is there a more elegant approach to assert the type TypeScript inferred for a specific variable? Currently, I am using the following method: function assertType<T>(value: T) { /* no op */ } assertType<SomeType>(someValue); This technique prov ...

Experience Next.js 13 with Chakra UI where you can enjoy Dark Mode without the annoying White Screen Flash or FOUC (flash of unstyled content)

Upon refreshing the page in my Next.js 13 /app folder application using Chakra UI, I notice a few things: A momentary white flash appears before switching to the dark theme. The internationalization and font settings momentarily revert to default before l ...

Creating a custom Angular 4 validator that relies on a service to access a list of valid values

I have a task to create a directive that validates whether an input value is part of a dynamic list of values. The list of values is passed as a parameter to the directive: @Directive({ selector: '[lookup]', providers: [{provide: NG_VALIDATORS, ...

Creating a currency input field in HTML using a pattern textbox

In a project using HTML, Angular 2, and Typescript, I am working with a textbox. How can I ensure that it only accepts numbers along with either one dot or one comma? The input should allow for an infinite number of digits followed by a dot or a comma and ...