Embedding an image by inserting the URL

I have been attempting to implement functionality in Typescript where an image preview appears after a user enters a URL, but I have only been successful in achieving this in JavaScript. My goal is to display a preview of the image and enable the user to upload it. I apologize for not providing more code, as I am still working on figuring it out.

upload.component.html

<input type="URL" id="myURL" placeholder="insert image URL here" (change)="onURLinserted($event) ">
        
        <button type="button" class="btn btn-dark btninput" [disabled]="toogleBool" (click)="onUpload()">Upload</button>
    

upload.component.ts

onURLinserted(event: any) {

    }
    

Answer №1

Here's a solution for you: I utilized two-way data binding to access your image URL and property binding in the image tag to bind your image.

HTML File,

<input type="URL" name="myURL" [(ngModel)]="myURL" placeholder="insert image URL here" (change)="onURLinserted() ">

<img [src]="imageToShow" alt="Place image title">

Typescript File,

imageToShow:any;
myURL:any

onURLinserted() {
      this.getImage(myURL).subscribe(data => {
        this.createImageFromBlob(data);
      }, error => {
        console.log("Error occurred", error);
      });
}

getImage(imageUrl: string): Observable<File> {
    return this.http
        .get(imageUrl, { responseType: ResponseContentType.Blob })
        .map((res: Response) => res.blob());
}

createImageFromBlob(image: Blob) {
   let reader = new FileReader(); //file reader needed to read blob data to base64 image data.
   reader.addEventListener("load", () => {
      this.imageToShow = reader.result; // result obtained from reader
   }, false);

   if (image) {
      reader.readAsDataURL(image);
   }
}

For more information, you can visit this link.

Getting Image from API in Angular 4?

Hope this helps to solve your issue.

Edit:-

import { Http,ResponseContentType } from '@angular/http';

constructor(private http: Http){}

   getImage(imageUrl: string): Observable<File> {
            let headers={ responseType: ResponseContentType.Blob }
            return this.http
                .get(imageUrl, headers)
                .map((res: Response) => res.blob());
        }

Give it another try,

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

Using ngFor to loop through an array of objects and calculate the number of elements in an array property

Currently I am developing a web application using Angular 6. The data is obtained in the form of an array of objects from Firebase, and my intention is to present this information to the user by utilizing ngFor. export interface Competition { createdAt: ...

Issue encountered while utilizing an observable object within a FormGroup

I've encountered an issue that I can't seem to resolve. I have a function that is responsible for creating my FormGroup along with the form fields and validators. The validators are custom validators that require a value from an observable, and t ...

Attaching an event listener to elements with a specified Class name

Currently facing a challenge where I am trying to implement a function that captures click events on squares. The objective is to capture the click event on every button with the square class. import { Component, OnInit } from '@angular/core&apos ...

Ways to implement pointer event styling within a span element

Hi, I'm having trouble with styling and I can't seem to figure out how to resolve it. The style pointer-events: none doesn't seem to be working for me. Here is an example of my code: The style snippet: .noclick { cursor: default; ...

Error encountered while attempting to load SWC binary for win32/ia32 in a Next JS application

Upon installing a Next.js app using the command npx create-next-app@latest, I encountered an error while running the app. Can anyone explain why this error occurred and provide a solution? PS D:\New folder\my-app> npm run dev [email pr ...

Error: The StsConfigLoader provider is not found! MSAL angular

I am currently using Auth0 to manage users in my Angular application, but I want to switch to Azure Identity by utilizing @azure/msal-angular. To make this change, I removed the AuthModule from my app.module and replaced it with MsalModule. However, I enco ...

The request/response is missing property "x" in type "y" but it is required in type "z" during fetch operation

I have configured an interface specifically for utilization with an asynchronous function: interface PostScriptTagResponse { script_tag : { readonly id : number , src : string , event : string , readonly created_at : string , readonl ...

Resetting an Angular form will clear the initially selected value

My application is built using Angular 4, and I have a select element inside my reactive form setup like this: <select class="form-control" formControlName="persons"> <option value="" selected>Select default</option> <option * ...

Problem with Angular's command line interface

I'm facing an unusual issue with angular/cli on my Windows machine. A year back, I installed Angular and created a new project successfully. I've been updating Angular whenever a new version is released (currently on v7). Today, when trying to cr ...

Communication between components through a shared service

Imagine you find yourself in one component and need to trigger a method from another component. There are multiple ways to achieve this, which are explained in more detail on this page. Here, I will demonstrate the simplest possible example of how to make ...

The Clarity Design side menu becomes unscrollable when the content is too long for the view

Currently, I am facing an issue with the sidenav where the navigation links go beyond the view and I am unable to scroll to see the "hidden" links unless I zoom out. My frontend framework is Angular 5 and this is how I organized the components: <nav c ...

How to specify the file path for importing a custom module?

I am currently learning Angular 2 and encountering an issue with importing a custom module that contains interface declarations. Here is my folder structure: https://i.stack.imgur.com/heIvn.png The goal is to import product.interface.ts into a component ...

Error TS2315: Invalid Type Assignment for Angular 6 ModuleWithProviders

Hey there, I'm encountering an issue that's got me scratching my head. I've shared some of my code in the hopes that it might shed some light on the problem. The problem cropped up as soon as I started working on a Reactive Form. Let me s ...

Angular fails to display newly created objects unless the page is manually refreshed

Hey there, I'm facing a problem with my message service on the user profile page. Even though messages are fetched from the database and displayed correctly, any changes (such as creating or deleting a message) are not reflected until I manually refre ...

When posting on social platforms, the URL fails to display any metadata

We recently completed a project (Web Application) using React .net core with client-side rendering in React. One challenge we encountered was that when the app loads in the browser, it only displays the static HTML initially without the dynamic meta tags. ...

Implement Cross-Origin Resource Sharing in Angular frontend

I am facing an issue with two microfrontends running on different ports (4200 and 4201) where one frontend is unable to access the translation files of the other due to CORS restrictions. To overcome this obstacle, I created a custom loader in my code that ...

Issue with Lodash in Angular 2 causing a Typescript error but still functional

While attempting to incorporate lodash into my angular2 project, I encountered an issue. Although it is functioning properly, I am consistently seeing the following error in my log: TS2307 Cannot find module 'lodash'. [error] import * as _ from ...

The data does not have a property named 'formData' according to the type 'Event'

Encountered an issue while attempting to compile my TypeScript code: typescript Property 'formData' does not exist on type 'Event'? formElem.addEventListener("submit", (e) => { // prevent default action on form submiss ...

Error: Router service provider not found in Angular 2 RC5!

Having trouble with using this.router.navigate. Here is the content of my app.module.ts file: import {NgModule, NgModuleMetadataType} from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; im ...

Adjust ion-select label width across the entire screen in Ionic version 6

I recently began working on a fresh project using Ionic v6. As part of the development, I included a basic ion-select element in my HTML code: <ion-item> <ion-select placeholder="Select Option"> <ion-select-opti ...