Obtain the reference to the child element of the nativeElement

As a newcomer to Angular, I am currently working with Angular 7. Within our project, we have implemented a button component labeled as "Send Email." When this button is clicked on the webpage where it is displayed, it triggers the default email sending window (such as Outlook or Gmail) enabling users to compose and send emails.

My current challenge involves obtaining a reference to the opened email dialog/window in order to track whether the email was successfully sent or cancelled. Additionally, I am looking to retrieve information about the recipient and subject line of the email. It seems that the type of my nativeElement is "<a>".

I have attempted to implement similar code like:

aDialog = this.dialog.open(aDialogComponent, dialogConfig);
aDialog.afterClosed().subscribe((data: EmailInfo) => {
    if (!data) {
        // Cancel button was clicked
        return;
    }
    this.to = data.to;
   this.from = data.from;
   this.subject = data.subject

   // Now log 
});

Is there a way to access the handle of the native email dialog and fetch the necessary fields for retrieving information?

Code snippets:

1> EmailLinkComponent.ts :

Note:

@ViewChild("sendEmail") sendEmailButton: ElementRef<HTMLAnchorElement>
and Onclick method

@Component({
  selector: "lib-email-link",
  templateUrl: "./email.link.component.html",
  styleUrls: ["./email.link.component.scss"]
})
export class EmailLinkComponent extends BaseComponent {
  private email: Email;
  @Input() from = "";
  @Input() to = "";
  @Input() tooltip = `Send email from this context (opens in default email client)`;
  @Input() pageContext: EmailPageContext = undefined;
  @ViewChild("sendEmail") sendEmailButton: ElementRef<HTMLAnchorElement>;
  mailToLink = "";

  constructor(private emailService: EmailService) {
    super();
  }

  onClick(): void {
    if (this.sendEmailButton) {
      this.sendEmailButton.nativeElement.click();
    }
  }
}

I tried modifying it as follows (which did not work):

onClick(): void {
    if (this.sendEmailButton) {
      this.sendEmailButton.nativeElement.addEventListener("close", (data: any) => {
        console.log("========>" + JSON.stringify(data));
      });
      this.sendEmailButton.nativeElement.click();
    }
  }    

2> email.link.component.html :

<span>
  <!-- Default "Send Email" button -->
  <button
    type="button" class="default-content btn-with-right-icon"
    mat-stroked-button color="accent"
    [matTooltip]="tooltip" matTooltipPosition="after" matTooltipShowDelay="1000"
    (click)="onClick()">
    Send Email
    <mat-icon>launch</mat-icon>
  </button>
</span>
<a #sendEmail style="display: none;" [href]="mailToLink"> </a>

3> This component can be used in parent HTML as shown below:

<lib-email-link #emailLink [pageContext]="PageEnum.context">
</lib-email-link>

Answer №1

Revised Answer:

Upon further review of your request, it appears that there is no direct way to verify if an email was sent from code. It would require manual intervention to handle the email sending process securely.

Allowing websites access to desktop applications like Outlook could pose serious risks such as unauthorized email sending and inbox reading.

To learn more about the limitations of browser JavaScript, you can visit https://javascript.info/intro#what-can-t-in-browser-javascript-do

You may be able to log details like the sender, recipient, and subject of the email in the mail client, but even this information may not guarantee secure usage.

Previous Response:

If you question the need for a button and link combination, consider simplifying the process by implementing a direct action like:

<a #sendEmail (click)="doClickStuff()" [href]="mailToLink" class="default-content btn-with-right-icon"> Send Email
<mat-icon>launch</mat-icon></a>

You can view a functioning example here: https://stackblitz.com/edit/angular-ivy-bytp4h

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

Ways to prevent an array from being reset

My issue involves the clothes and orders tables, along with an array based on Clothes and Orders models. Whenever I add a clothes element into the Orders array and specifically update the amount and price of the selected item, it also updates the Clothes a ...

To dismiss the Div, simply click on any area outside of it. Leveraging the power of SVG, D3

I need a way to hide my div by clicking outside of it. My SVG has a background and a graph with nodes on top of that. I have a special node (circle) on the graph, clicking on which makes a box appear. To show the box, I use the following code: d3.select ...

Is it necessary to 'type assert' the retrieved data in Axios if I have already specified the return type in the function declaration?

Consider the code snippet below: import axios from 'axios' async function fetchAPI<T>(path: string, data: any): Promise<T> { return (await axios.get(path, data)).data as T } async function getSomething(): Promise<SomeType> { ...

There is no redirection or component available for the specified path in angular2

What is the best way to handle a routes array with an empty string path in order to make it essentially do nothing? I'm not looking to redirect or load a component. Removing the object from the array works fine, but generates console errors that I&apo ...

Error in Template Syntax for External Pug Templates: Component template must have a root element, not just plain text

I've been struggling to make Pug templates work with Vue class-based components using a separate file for the pug template. The documentation suggests that adding this code should do the trick: // webpack.config.js -> module.rules { test: /&bsol ...

Creating a Typescript class to mirror the Mongoose model

Currently, I am working on a web application utilizing Angular 2 with TypeScript. The database I am using is MongoDB with a Mongoose framework, and the server is running on Node with an Express framework. The MongoDB and Node code is written in plain JavaS ...

Comprehending TypeScript: Dealing with parameters that cannot be assigned

Let's consider the following scenario: const client: Client | boolean = await db.connect() if (client === false) { return } await start(client) The function db.connect() returns either a Client on successful connection or false in case of failure ...

Incorporate a cutting-edge Progressive Web Application into your repertoire on the Play

Our Progressive Web App (PWA) is built entirely using the new Angular framework. We have implemented various optimizations such as tree shaking, uglify, AOT, and service worker to ensure it functions smoothly and performs like a mobile app. When users add ...

The error thrown by Mongoose, stating "TypeError: Cannot read property 'catch' of undefined," is not caught after the data is saved

After updating to Mongoose version 5.0.15, I encountered an error that says TypeError: Cannot read property 'catch' of undefined when trying to save my object with errors found, even though everything was working fine on Mongoose version 4.13.11. ...

Transferring information to a complex and deeply embedded Angular component

In my current component structure, A includes B, B includes C, and C includes D. I am looking to transfer data from the topmost component (A) to the one at the bottom of the hierarchy (D). Should I utilize data binding in HTML templates, which would requ ...

An effective approach to positioning HTML elements at specific X and Y coordinates

I have an innovative project idea! The concept is to enable users to create points by clicking on the display. They can then connect these points by clicking again. However, I am facing a challenge when it comes to creating HTML elements at the exact loc ...

The 'IncomingHttpHeaders' type cannot be assigned to the 'BusboyHeaders' type

I am currently using the busboy module in my TypeScript/Node project for file uploading. In all the documentation for busboy, they suggest initializing it with request headers. However, I am encountering the following error: Type 'IncomingHttpHeaders& ...

Generate iframes dynamically in Angular Fire by retrieving data from a database query, dealing with the unsafe value using DOM Sanitization

Currently, I am using Ionic and Angular with Firebase to develop a daily readings application that dynamically displays an iframe for embedded YouTube videos based on the date. Everything works fine until I try to use data bindings in the source URL for th ...

Issues arise when Angular is unable to establish a connection with the backend server written in Golang

Using nginx to serve angular (index.html) is working fine. However, I keep encountering errors when attempting to communicate with my backend. Dockerfile Setup for NGINX + Angular FROM node:12-alpine as builder WORKDIR /usr/src/app COPY . . RUN npm instal ...

Manipulate the name of a property or field using TypeScript

I am in the process of creating a bilingual blog using Nuxt.js and TypeScript. This application interacts with a REST API to retrieve data that is structured like this: { "Headline_de": "Mein erster Blogpost", "Headline_en" ...

What is the significance of parentheses when used in a type definition?

The index.d.ts file in React contains an interface definition that includes the following code snippet. Can you explain the significance of the third line shown below? (props: P & { children?: ReactNode }, context?: any): ReactElement<any> | nu ...

There is no registered handler for channel - Electron IPC handle/invoke

When using my Electron app, I keep encountering the error message "No handler registered for 'channel-name' at EventEmitter../lib/renderer/api/ipc-renderer.ts.ipcRenderer.invoke (electron/js2c/renderer_init.js:1163:19)". This issue seems to stem ...

webpack - compile one TypeScript file separately (2 actions)

In summary... When my Vue files are combined with background.ts, webpack processes them to create bundled vue files along with background.js I'm unable to run the background.js script I expected background.js to only contain "console.log(' ...

Utilize Angular to associate a value with a directive parameter

I'm currently working on a directive that will alter the text of a button based on a specific condition. For instance, during the saving process of a form, I want the submit button to display "Saving..." until the processing is complete, and then reve ...

Getting an error with TypeScript and React refs: Cannot access property 'current' when it's undefined

I am currently developing a React application using TypeScript. One of the features I want to implement is a button that scrolls to a specific header in a child component on the main page. To achieve this, I have created a reference in the child componen ...