What is the best way to transfer a function between components in Angular?

In my driver-list.component.html file, the code snippet below is present:

<button class="btn btn-outline-primary mr-2" (click)="open('focusFirst')">
  <div>Open confirm modal</div>
  <div class="text-dark" aria-hidden="true"><small>&times; button will be focused</small></div>
</button>

Here is my updated driver-list.component.ts:

UPDATED driver-list.component.html

    @Component({
  selector: 'app-driver-list',
  templateUrl: './driver-list.component.html',
  styleUrls: ['./driver-list.component.css']
})
export class DriverListComponent implements OnInit {

  ...

@Component({
  selector: 'ngbd-modal-confirm',
  template: `
    <div class="modal-header">
      <h4 class="modal-title" id="modal-title">Profile deletion</h4>
      <button type="button" class="close" aria-describedby="modal-title" (click)="modal.dismiss('Cross click')">
        <span aria-hidden="true">&times;</span>
      </button>
    </div>
    <div class="modal-body">
      <p><strong>Are you sure you want to delete <span class="text-primary">"John Doe"</span> profile?</strong></p>
      <p>All information associated to this user profile will be permanently deleted.
        <span class="text-danger">This operation can not be undone.</span>
      </p>
    </div>
    <div class="modal-footer">
      <button type="button" class="btn btn-outline-secondary" (click)="modal.dismiss('cancel click')">Cancel</button>
      <button type="button" class="btn btn-danger" (click)="modal.close('Ok click')">Ok</button>
    </div>
  `
})
export class NgbdModalConfirm {
  constructor(public modal: NgbActiveModal) {}
}

const MODALS: {[name: string]: Type<any>} = {
  focusFirst: NgbdModalConfirm
};

@Directive({
  selector: "[openClick]",
})
export class NgbdModalFocus {
  @Input() name!: string;
  withAutofocus = `<button type="button" ngbAutofocus class="btn btn-danger"
      (click)="modal.close('Ok click')">Ok</button>`;

  constructor(private _modalService: NgbModal) {}

  @HostListener("click", ["$event"])
  open(name: string) {
    this._modalService.open(MODALS[name]);
  }
}

The modal currently appears empty. I need to add content to the other two components as well in order to format the modal messages. Should directives be used there too?

Answer №1

Directives serve a crucial purpose in Angular!

import { Directive, Input, HostListener } from "@angular/core";

@Directive({
  selector: "[openClick]",
})
export class open {
  @Input() name: string;

  constructor(
    private _modalService: NgbModal
  ) {}

  @HostListener("click", ["$event"])
  open(event) {
     this._modalService.open(MODALS[this.name]);
   }
}

To use the directive on your button:

<button class="btn btn-outline-primary mr-2" openClick name="focusFirst">
  <div>Open confirm modal</div>
  <div class="text-dark" aria-hidden="true"><small>&times; button will be focused</small></div>
</button>

<button class="btn btn-outline-primary" openClick name="autoFocus">
  <div>Open confirm modal with `ngbAutofocus`</div>
  <div class="text-dark" aria-hidden="true"><small>Ok button will be focused</small></div>
</button>

For more information on directives, check out the official documentation here: https://angular.io/api/core/Directive

Remember to create directives separately and import them into the necessary modules.

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

Calculating the annual total in angular 4 - a step-by-step guide

I have successfully calculated the sum of costs between each other, but now I am facing a challenge in summing up the total budget for the entire year. I have attempted to achieve this, but unfortunately, I am encountering an issue as it is showing me &apo ...

Error in Angular Module 'AppModule' importing an unexpected value of 'undefined'?

My current setup involves using ngModule to organize imports and dependencies, with ag grid serving as the data grid component. Here is a snippet from my app.module.ts file: import { NgModule } from '@angular/core'; import { BrowserModule } ...

Guide to creating a one-to-one object literal map with a different value type using a function return without explicitly defining the return type

At the moment, I have successfully managed to combine the keys and values of each object literal that is passed into a function. For example: interface StaticClass<T = any> { new (...args: any[]): T } type RecordOfStaticClasses = Record<string, ...

I am encountering difficulties in choosing options from the mat-select menu and am unable to display the selected option in the console

Can someone help me with this issue? I have a dropdown list with 2 items and I want the first one to be pre-selected. When either option is selected, I need its value to be displayed in the console and saved in a variable. Here's the code snippet: HT ...

Issue with incorrect inference of TextField `helperText` when using Formik with Material-UI

Upgrading to react-scripts 5 has caused an issue with the helperText on the TextField component. My TypeScript knowledge is not strong, so I'm having trouble fixing it. Here's more information about the problem: The error message: TS2322: Type & ...

Encountering "Error: Class constructor vA cannot be invoked without 'new'" when using Angular 10 Kendo Grid

I am currently working on integrating a Kendo Grid into my Angular application. However, I have run into an error when enabling the Kendo Grid component: vendor.4add67dadae0cd9152b9.js:16 ERROR Error: Uncaught (in promise): TypeError: Class constructor vA ...

What is the destination for the installation of Angular-cli?

Is it possible to install Angular-cli in a specific location? Can I execute Angular-cli commands without installing it globally? ...

Creating a Build-Free Workflow in a TypeScript Monorepo

Imagine having this monorepo structure: /apps /apps/app1 /apps/app1/src (includes index.ts and various other files and subdirectories) /apps/app1/tsconfig.json /apps/app1/package.json /apps/app2 /apps/app2/src (contains index.ts and many other files an ...

Is the dist folder included in the Angular package on NPM and GIT repository?

My Objective: I have developed an Angular module and I aim to install it from my GIT repository using npm install in other projects without needing to use npm publish due to the private nature of the code. To achieve this, I am utilizing ng-packagr (http ...

How can I leverage a public API in Angular 6 to create a custom database for my application?

Currently, I am developing an Angular 6 project and I have a query regarding the possibility of obtaining data from both a public API and an in-memory database simultaneously. For example, displaying movies from a public API while also allowing users to ad ...

Using Angular's RxJs: A BehaviorSubject can trigger an HTTP request, which in turn triggers the next value

i'm facing an issue with circular dependency. I attempted to use switchMap(() => EMPTY), take(1) approach to resolve it. While this solution works, it's not ideal. Here's a snippet of the code: P.S. ConstructorGeneratorService creates a ...

The Bootstrap modal fails to appear when closed

After opening and closing the modal window, clicking on the button does not display the modal window again. The screen remains grayed out and the content of the modal window does not appear. yyyyyyyyyyyyyyyy function customShortcode() { ob_start(); ...

"Learn how to utilize array values in TypeScript to easily display them using NgFor in HTML

Looking for a solution: <select (change)="getYear(year)"> <option value="year" *ngFor="let var of array; let i = index" {{year.year}} </option> </select> Is there a way to configure the typescript code so that I can dynamica ...

Angular: The object cannot be extended to add the property resumeBootstrap

I encountered an issue with my upgrade / hybrid AngularJS / Angular 2 application where an error message appeared: Unhandled Promise rejection: Cannot add property resumeBootstrap, object is not extensible ; Zone: ; Task: Promise.then ; Value: Type ...

I am deciding between using CommonJS or ES module for my sub packages in a Yarn workspace for my Next.js project. Which one

Currently working on a Next.js monorepo project using TypeScript and yarn workspace. Within the yarn workspace, there are two packages: /web and /api. The /web package is a next.js project, while /api serves as a shared subpackage utilized by /web. /my-pr ...

"Encountering an error with _getHostElement in Angular Material's experimental mat-slider component. Looking for a solution

Recently, I made the switch to Angular 12 and decided to explore the new mat-slider in Angular Material Experimental. My goal was to have a range slider, but since it's not currently available in the regular Angular Material package, I wanted to stick ...

Adding dynamic row values to a bootstrap table in angular 4 - what's the best approach?

When using an Angular 4 bootstrap table, I am encountering an issue where only the first row value is displayed in the table from the backend when entering a product in the text box and pressing enter. Even though the alert window shows the data for the se ...

Troubleshooting problem with thumbnail view feature for PDF files on Angular 2 platform

Recently I started working with angular 2 and encountered an issue while trying to upload a PDF file and display its thumbnail in the UI using ng2-pdf-viewer. The error message I'm facing is: AppComponent.html:10 ERROR Error: Invalid parameter object ...

Utilize Webpack to dynamically load specific angular-i18n locale files and minimize file overhead

Currently utilizing Webpack version 2.3.3 along with Babel-loader As a newcomer to Webpack, I am in the process of bundling angular-i18n locale files using Webpack. I have a configuration object that outlines the supported locales for the application: va ...

Exploring the parent-child relationship of three components within Angular 2

Currently, I am developing a shopping cart using Angular 2. The application consists of two components - one for categories and another for product listings, both included in the main app component as children. However, I'm facing an issue where these ...