What is the best way to transfer an image between Angular components and then showcase it?

I've developed a feature using an observable and I'm attempting to transfer a dataURL from one component to another in order to display it as an image.

Here is the HTML code for the component where I want to send data from:

<canvas id="patternFrame" width="600px" height="600px"></canvas> 
<ion-button color="medium" (click)='sendPattern()'>send</ion-button>

This is the Typescript code for the component where I want to send data from:

import {StageColorService} from '../../services/stage-color.service';

  constructor(private stageColorService: StageColorService){}

 ngOnInit(){}

  sendPattern(){
    const canv =document.getElementById('patternFrame') as HTMLCanvasElement;
    this.stageColorService.sendStage(canv.toDataURL()); // utilizing service to transmit image to color component
  };

Below is the HTML code for the component where I want to send data to:

<img src="" alt="Image" id="onlyImage" width="400" height="200">

And here is the Typescript code for the component where I want to send data to:

import {StageColorService} from '../../services/stage-color.service';

  constructor(private stageColorService: StageColorService) { }

  ngOnInit() {

    this.stageColorService.stage$
        .subscribe(
          image => {
            console.log('image subscription'+ image);
              document.getElementById('onlyImage').setAttribute('src',  image);
            });
  }

Lastly, this is the Typescript code for my service:

import { Injectable } from '@angular/core';
import {Subject} from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class StageColorService {

  private stageSource = new Subject<any>();
  stage$ = this.stageSource.asObservable();

  constructor() { }

  sendStage(st: any){
    this.stageSource.next(st);
  }
}

Answer №1

Please refrain from using

document.getElementById('onlyImage').setAttribute('src',  image);

Instead, it is recommended to assign the image source to a variable. For example:

import {StageColorService} from '../../services/stage-color.service';

public imgSrc:string;

constructor(private stageColorService: StageColorService) { }

ngOnInit() {

this.stageColorService.stage$
    .subscribe(
      image => {
        console.log('image subscription'+ image);
          this.imgSrc = image
        });
}

In your HTML file, use:

<img [src]="imgSrc" alt="Image" id="onlyImage" width="400" height="200" />

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

When trying to import a module in Angular, an error is encountered while using Scully

Exploring the utilization of Scully within my Angular project has presented me with a challenge. In Angular, Modules must be imported in order to use them effectively. However, when attempting to execute Scully through the command line: npm run scully --sc ...

Angular4: Sharing breadcrumb view components via the router's `data` attribute

Currently in my Angular app (Angular v4), I'm working on developing a breadcrumb module. After coming across this insightful question on Stack Overflow, I learned about storing breadcrumb information in the router's data property as shown below: ...

Discover the Phillips Hue Bridge within the operational web application on a separate network

Utilizing the node-hue-api package on a Node.js/Express server to interact with the Hue API, I've developed an admin section of a website exclusively accessible to me for controlling my Hue lights. The functionality works seamlessly in my local develo ...

Troubleshooting compilation problems in Angular2 with nested components

I have created two components in Angular2 using TypeScript: app/app.component.ts import { Component } from '@angular/core'; @Component({ selector: 'my-app', styles : [` .parent { background : #c7c7c7; ...

Converting a TypeScript nested dictionary into a list of strings

I am currently working with a nested dictionary and my goal is to convert it into a list of strings. For example, the initial input looks like this: var group = { '5': { '1': { '1': [1, 2, 3], ...

Using Angular's ng-switch directive within a select dropdown option

Can we implement the [Data Presentation Format] to be utilized in the [Dropdown Box]? Specifically, I would like the "parent" items to appear as is within the dropdown, while the "child" items should have a [tab] indentation to denote their relationship wi ...

How to position button components at the center in a NextJS application?

Incorporating a button within my nextjs page has been a challenge as I am striving to position it in the center of the page for optimal viewing on both PCs and mobile devices. Despite various attempts, the button remains fixed on the far left side of the p ...

What could be causing this JavaScript code to run sluggishly in Internet Explorer despite its simple task of modifying a select list?

I am currently developing a multi-select list feature where users can select items and then rearrange them within the list by clicking either an "Up" or "Down" button. Below is a basic example I have created: <html> <head> <tit ...

Nextjs is facing challenges in enhancing LCP specifically for text content

I've been trying to boost my LCP score by optimizing the text on my page, but it seems stuck and I can't figure out why my LCP isn't improving. Take a look at the screenshot: https://i.stack.imgur.com/xfAeL.png The report indicates that &a ...

Bidirectional Data Binding in AngularJS

In my angular application, there is a dropdown with various values. When a user selects a specific value from the dropdown, I want to display the complete array corresponding to that value. <!doctype html> <html lang="en"> <head> < ...

The React DOM isn't updating even after the array property state has changed

This particular issue may be a common one for most, but I have exhausted all my options and that's why I am seeking help here. Within my React application, I have a functional component named App. The App component begins as follows: function App() ...

What is the process for the event loop moving into the poll phase?

There is a scenario outlined in the event loop explanation on the Node.js official website. When setTimeout is triggered, and the callback queue for the timer phase isn't empty, why does the event loop move on to the poll phase? The site mentions that ...

Guide on utilizing the h function in Vue3 for seamless binding and passing of properties and events from parent to child components

Utilizing Vue3 and naive ui for front-end development has been a challenge for me as I primarily focus on back-end development and lack expertise in front-end technologies. To enhance user interaction, I incorporated naive ui’s BasicTable along with an ...

What is the process through which React form elements receive the event parameter?

I'm currently working on a form component that looks like this: import React from 'react'; class CommentBox extends React.Component { constructor(props) { super(props); this.state = { value: '' } this.han ...

employing a variable within a function that is nested within another function

I'm encountering an issue where I am using a variable within a nested function. After assigning a value to it, I pass it to the parent function. However, when I call the function, nothing is displayed. function checkUserExists(identifier) { let user ...

The PKIJS digital signature does not align with the verification process

Explore the code snippet below const data = await Deno.readFile("./README.md"); const certificate = (await loadPEM("./playground/domain.pem"))[0] as Certificate; const privateKey = (await loadPEM("./playground/domain-pk ...

Implementing AngularJS table filters on user click

As a newcomer to angularjs, I am attempting to implement a filter on click. The user will select a source and destination, then click on the filter button. The table should display results based on the input. Upon page load, the table should already contai ...

Angular 2 does not update the variable value within a dataservice call on the page until you navigate away from the page and then come back to it

Currently, I am working with Angular2 and have encountered a strange issue. I have a variable that I display on the page, and when a button is clicked, a data service is called to update the value of this variable. Surprisingly, even after changing the val ...

Steps for implementing remote modals in Bootstrap 5 using CS HTML

I'm attempting to implement a remote modal window in Bootstrap 5 with C# MVC. The endpoint for the modal partial view is configured correctly. According to this discussion on Github, all that needs to be done is to call some JavaScript. However, it ...

Utilizing inputRef in conjunction with MUI's useAutocomplete

Is there a way to pass the "inputRef" to Material UI's useAutocomplete? I'm looking to set a custom reference on the input, but the getInputProps() method from useAutocomplete already requires its own reference. I've attempted various appr ...