Tips for transferring the "close" function from a modal template to the HTML of another component in Angular 5

Recently, I started learning angular 4 and I need some assistance with a specific issue. I have a component that contains a modal template.

Component :-

import {Component} from '@angular/core';

import {NgbModal, ModalDismissReasons} from '@ng-bootstrap/ng-bootstrap';

@Component({
  selector: 'ngbd-modal-basic',
  templateUrl: './modal-basic.html'
})
export class NgbdModalBasic {
  closeResult: string;

  constructor(private modalService: NgbModal) {}

  open(content) {
    this.modalService.open(content).result.then((result) => {
      this.closeResult = `Closed with: ${result}`;
    }, (reason) => {
      this.closeResult = `Dismissed ${this.getDismissReason(reason)}`;
    });
  }

  private getDismissReason(reason: any): string {
    if (reason === ModalDismissReasons.ESC) {
      return 'by pressing ESC';
    } else if (reason === ModalDismissReasons.BACKDROP_CLICK) {
      return 'by clicking on a backdrop';
    } else {
      return  `with: ${reason}`;
    }
  }
}

Html :-

<ng-template #content let-c="close" let-d="dismiss">
    <app-partial-modal-content></app-partial-modal-content>
</ng-template>

Another component named PartialModalContentComponent

import { Component, OnInit } from '@angular/core';

import { NgbModal, ModalDismissReasons } from '@ng-bootstrap/ng-bootstrap';

@Component({
  selector: 'app-partial-modal-content',
  templateUrl: './partial-modal-content.component.html',
  styleUrls: ['./partial-modal-content.component.css']
})
export class PartialCloneModalComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}

and partial-modal-content.component.html is

<div class="modal-header">
  <h4 class="modal-title">Modal title</h4>
  <button type="button" class="close" aria-label="Close" (click)="d('Cross click')">
    <span aria-hidden="true">&times;</span>
  </button>
</div>
<div class="modal-body">
  <p>One fine body&hellip;</p>
</div>
<div class="modal-footer">
  <button type="button" class="btn btn-outline-dark" (click)="c('Close click')">Close</button>
</div>

However, when attempting to close this modal, an error appears in the console stating that d and c are not functions. I aim to pass the template's let-c="close" let-d="dismiss" to another component. How can I accomplish this?

Answer №1

In order to access data in your PartialModalContentComponent class, you can declare a @Input().

import { Component, OnInit, Input } from '@angular/core';

import { NgbModal, ModalDismissReasons } from '@ng-bootstrap/ng-bootstrap';

@Component({
  selector: 'app-partial-modal-content',
  templateUrl: './partial-modal-content.component.html',
  styleUrls: ['./partial-modal-content.component.css']
})
export class PartialCloneModalComponent implements OnInit {
@Input() cValue;
@Input() dValue;

 constructor() { }

  ngOnInit() {
  }

}

When inserting it into your html, use the following:

<ng-template #content let-c="close" let-d="dismiss">
    <app-partial-modal-content [cValue] = "this.c"></app-partial-modal-content>
</ng-template>

Now you have access to cValue in both your tsfile and html file within PartialModalContentComponent.

Answer №2

To ensure proper functionality, it is essential to create a "handlerClose" function in your partial-modal-content TypeScript file. This function must be triggered from both the dismiss button with the label "Cross click" and the footer close button labeled 'Close click'. Subsequently, you need to emit the text to the output field "close". In the "ngbd-modal-basic" component, define the output (close) that invokes another function to display the specific text returned. Refer to the example provided below.

// partial-modal-content.component.html 
<div class="modal-header">
  <h4 class="modal-title">Modal title</h4>
  <button type="button" class="close" aria-label="Close" (click)="handlerClose('Cross click')">
    <span aria-hidden="true">&times;</span>
  </button>
</div>
<div class="modal-body">
  <p>One fine body&hellip;</p>
</div>
<div class="modal-footer">
  <button type="button" class="btn btn-outline-dark" (click)="handlerClose('Close click')">Close</button>
</div>

//partial-modal-content.component.ts
@Component({
  selector: 'app-partial-modal-content',
  templateUrl: './partial-modal-content.component.html',
  styleUrls: ['./partial-modal-content.component.css']
})
export class PartialCloneModalComponent implements OnInit {
  @Output() close = new EventEmitter();
  constructor() { }
  ngOnInit() {  }

  handlerClose(template){
    this.close.emit(template);
  }
}

// ngbd-modal-basic
<ngbd-modal-basic(close)="handleClose($event)"></ngbd-modal-basic>

@Component({
  selector: 'ngbd-modal-basic',
  templateUrl: './modal-basic.html'
})
export class NgbdModalBasic {
    closeResult: string;

    handleClose(e){
        this.closeResult = e;
    }
}

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

Issues arise when attempting to override attributes within the HTML of a parent component in Angular

Why does overriding an attribute in a child class that extends from another not work as expected? Here's a made-up scenario to simplify the issue: Parent class file: gridbase.component.ts import { Component, OnInit } from '@angular/core'; ...

Unable to locate the _app.js file within my Next.js project

After using "npx create-next-app" to set up my NextJs project, I came across a situation where I needed to define TransactionContext in _app.js. However, I encountered the issue that this file is not included in my project. Any assistance would be greatly ...

Incorporating modules through System.JS

I integrated angular2-google-maps into my Angular 2 application for utilizing Google Maps functionality. Here is a snippet from my package.json: { "name": "angular2-quickstart", "version": "1.0.0", "scripts": { "start": "tsc && concurre ...

Troubleshooting Typescript compilation issues following an upgrade to a React Native project

I am facing a challenge while updating a react native project from version 0.63.3 to 0.67.0. When attempting to run npm run tsc, I encounter numerous errors indicating that the typescript packages are not compatible with their original packages. Here is a ...

Tips for conducting tests on an Observable<boolean>

I am facing an issue with handling an Observable in my code. Here is a snippet of the relevant parts: app.component.ts import { Observable } from "rxjs"; export class ProductComponent implements OnInit { ProductListLength: Num ...

Ways to sort through a Unix timestamp

Recently, I encountered an issue with my Ionic mobile application. It has a search button and filter feature that works well for filtering words. However, the problem arises when it comes to filtering dates displayed in the app as timestamps using Angular ...

Problem: NgFor is failing to render the data

Hey there! I'm working on a project that involves Spring Boot, SQL, and Angular. I have set up one-to-many relationships, but I'm struggling to display the second object in my component's HTML. Here's my current setup: @Component({ se ...

Issue with bi-directional data binding in Angular's matInput component

When working on my template... <input matInput placeholder="Amount" [(value)]="amount"> In the corresponding component... class ExampleComponent implements OnInit { amount: number = 0; ... } The binding doesn't seem to work as expect ...

Toggle the Visibility of your Password

I am currently working on implementing a TypeScript function in my webpage to enable the toggling of password visibility using an icon. The desired functionality is as follows: when a button (in this case, a clickable icon) is pressed, the icon should chan ...

Error: Unable to load chunk.js in Angular 7

After upgrading to Angular 7, I've been diving into the world of Lazy loaded modules. However, despite my efforts, I can't seem to find #chunk.js anywhere in the network tab when I click on components within the lazy loaded module. Even when Con ...

Steps to eliminate the Bearer authorization header in an Angular 4 POST request to an API

Is it possible to exclude the Authorization Bearer in a POST request? The following code was not successful in removing the authorization bearer that is being added by the HTTP interceptors. Error: 403 - Unauthorized Request. The Authorization header is ...

Hovering over a row in a p-dataTable (primeNg) triggers a mouse-over event

Working on the user interface for my web application in angular2, I am currently using a p-dataTable component from primeNG. I am looking for a way to trigger a function when the mouse hovers over a row in this dataTable. The function should be able to ret ...

What is the reason why the [active] attribute does not function properly in <a mat-tab-link> in Angular?

<div class="d-flex d-column themed-tab-nav"> <nav mat-tab-nav-bar color="primary" [tabPanel]="tabPanel" mat-stretch-tabs="false" mat-align-tabs="start"> <a mat-tab-l ...

Ways to capture targeted requests

Utilizing NestJS and Angular 2, I have noticed that both frameworks have a similar approach when it comes to working with Interceptors. I am currently looking for the best practice to identify specific requests in order to perform additional tasks. When d ...

Replace Nebular theme with a new design for a single component

I am currently using Nebular in my Angular application and I am trying to figure out how to customize the theme settings for a specific component on just one page, without affecting other instances of the same component that are using the default settings. ...

Using *ngFor to populate an array in an ion-list within Ionic 2

Hi there, I'm currently learning Ionic 2 and I recently created an array that I want to loop through in an ion-list. This is my produk.ts import { Component } from '@angular/core'; import { NavController, NavParams } from 'ionic-angul ...

Having difficulty constructing a full stack application using Express

I've been struggling to configure a full stack app using create-react-app with Express and TypeScript. My main issue is figuring out how to compile the server files into a build folder. I have separate tsconfig files for the server and create-react-ap ...

Weird occurrences in Typescript generics

function resizeImage<T extends File | Blob>(input: T, width: number, height: number): Promise<T> { return Promise.resolve(new File([new Blob()], 'test.jpg')) } Error: (48, 3) TS2322:Type 'Promise' is not assignable to ...

Angular - Bootstrap modal displays as a standalone element rather than a dialog box

Currently working on my initial Angular project, I am attempting to incorporate a dialog that prompts for confirmation before deleting an item. Utilizing ng-bootstrap, I referred to the examples in the documentation as my starting reference. The issue I a ...

Having trouble installing sub npm dependencies for a private npm module

I've created an npm private repository using Sinopia and published an app that is a complete end-to-end application built with Angular2 on the UI side. The package.json file contains dependencies such as @angular/core and animations. However, when I ...