HostListener not being listened on CdkDragDrop event using custom directive Angular6 - drag-and-drop

I am working with angular6 CdkDragDrop module.
I tried to create a custom directive "appRenderControl" that
would listen to CdkDragDrop event, when an item is dropped into
the container.
However, the directive is not being listened at the
moment.
Below is my code, can anyone please point out what is going wrong.
<div id='main'>
<div [style.background]="'blue'" id='components'>
<mat-card>
<mat-card-title>Components</mat-card-title>
<mat-card-content >
<div id="controls" cdkDropList #inactiveList="cdkDropList"
[cdkDropListConnectedTo]="[activeList]">
<div class="control-button" *ngFor="let item of controls" cdkDrag >
<div class="custom-drag-drop" *cdkDragPlaceholder>{{item}} </div>
{{item}}
</div>
</div>
</mat-card-content>
</mat-card>
</div>
<div [style.background]="'white'" id='preview' cdkDropList
#activeList='cdkDropList' appRenderControl>
</div>
</div>
</div>
</div>
Directive.ts
import { Directive, HostListener} from '#angular/core';
import {CdkDragDrop} from '#angular/cdk/drag-drop';
#Directive({
selector: '[appRenderControl]'
})
export class RenderControlDirective {
constructor() {
}
//This is not being listened
#HostListener('CdkDragDrop', ['$event'])
onItemDropped(event: CdkDragDrop<string[]>): void {
console.log('directive being called')
}
}

Related

Load a component inside modal and pass data back

I have a component A which has a button that launches a modal dialog that renders component B. In the modal dialog the user can take some action in component b and I want a value from component b to be accessible in component A when dialog dismisses.
a.component.html
<ng-template #lookupCustomerDialog let-modal>
<div class="modal-body">
<form>
<div class="form-group">
<app-component-b></app-component-b>
</div>
</form>
</div>
</ng-template>
when user dismisses the dialog above I want a value from app-component-b to be available in component a
I'm using EventEmitter to solve this:
A.Component.ts
export class ComponentA implements OnInit {
sampleFuncInAComponent(data: any) {
/*your codes that using data from component b*/
}
}
B.Component.ts
import {Component, OnInit, Output, EventEmitter} from '#angular/core';
export class ComponentA implements OnInit {
#Output() sendDataEvent = new EventEmitter();
myData;
onSendDataFunc() {
this.sendDataEvent.emit(this.myData);
}
}
A.Component.html
<ng-template #lookupCustomerDialog let-modal>
<div class="modal-body">
<form>
<div class="form-group">
<app-component-b (sendDataEvent)="sampleFuncInAComponent($event)"></app-component-b>
</div>
</form>
</div>
</ng-template>

Angular Drag and drop is not working if using *ngFor in cdkDropList

I was tried to using angular material drag and drop and I was looping through cdkDropList container. I'm not able to drag the items from Catalogue to (to do )list. If I'm not using any loop then it's working fine.
Here is my stackblitz link
I tried without loop that is working fine
<div cdkDropList #todoList="cdkDropList" [cdkDropListData]="todo" [cdkDropListConnectedTo]="[done]" [id]="item"
class="column-list" (cdkDropListDropped)="drop($event)"
<div class="column-box" [ngClass]="[(item.Name=='R') ?'Red':'',(item.Name=='G') ?'Green':'',(item.Name=='B') ?
'Blue':'',(item.Name=='Y') ?'Yellow':'',(item.Name=='O') ?'Orange':'']" *ngFor="let item of items3" cdkDrag cdkDragLockAxis="y">
{{item.Name}}</div>
</div>
but if I'm adding this *ngFor it's not working
<div cdkDropList #todoList="cdkDropList" [cdkDropListData]="todo" [cdkDropListConnectedTo]="[done]" [id]="item"
class="column-list" (cdkDropListDropped)="drop($event)" *ngFor="let item of signalContainer">
<div class="column-box" [ngClass]="[(item.Name=='R') ?'Red':'',(item.Name=='G') ?'Green':'',(item.Name=='B') ?
'Blue':'',(item.Name=='Y') ?'Yellow':'',(item.Name=='O') ?'Orange':'']" *ngFor="let item of items3" cdkDrag cdkDragLockAxis="y">
{{item.Name}}</div>
</div>
COMPONENT.TS
import {Component} from '#angular/core';
import {CdkDragDrop, moveItemInArray, transferArrayItem} from '#angular/cdk/drag-drop';
#Component({
selector: 'cdk-drag-drop-connected-sorting-example',
templateUrl: 'cdk-drag-drop-connected-sorting-example.html',
styleUrls: ['cdk-drag-drop-connected-sorting-example.css'],
})
export class CdkDragDropConnectedSortingExample {
initialSkeleton = new Array(5);
done = [
'A','B','C','D','E'
];
drop(event: CdkDragDrop<string[]>) {
if (event.previousContainer === event.container) {
debugger;
moveItemInArray(event.container.data, event.previousIndex, event.currentIndex);
} else {
event.container.data[event.currentIndex] = event.previousContainer.data[event.previousIndex];
}
}
}
HTML
<div class="example-container">
<h2>To do</h2>
<div cdkDropList #todoList="cdkDropList" [cdkDropListData]="initialSkeleton" [cdkDropListConnectedTo]="[doneList]" class="example-list"
(cdkDropListDropped)="drop($event)">
<div class="example-box" *ngFor="let item of initialSkeleton" cdkDrag>
<div class="child" >{{item }}</div>
</div>
</div>
</div>
<div class="example-container">
<h2>Done</h2>
<div cdkDropList #doneList="cdkDropList" [cdkDropListData]="done" [cdkDropListConnectedTo]="[todoList]" class="example-list"
(cdkDropListDropped)="drop($event)">
<div class="example-box" *ngFor="let item of done" cdkDrag>{{item}}</div>
</div>
</div>
I've modified the code now you will be able to drag and drop items in the for loop. Hope it answers your question.

angular 5 form with form builder

I am trying to implement a form in Angular5. But there occurs a error in the console which states 'formGroup needs to have an instance of FormGroup'
This is the HTML code:
<form [formGroup]="userInfo" (ngSubmit)="onSubmit()" novalidate>
<div class="input-section">
<div class="form-group filled-form">
<label for="businessName">What positions are you hiring for?</label>
<input class="form-control myInputStyle" type="text" id="enterEmail"
formControlName="businessname" required>
<div [hidden]="userInfo.controls['businessname'].valid ||
userInfo.controls['businessname'].pristine" class="inline-error">
Please enter a Business name!
</div>
</div>
</div>
</form>
Here is the ts code :
export class HwaPreviewComponent implements OnInit {
public userInfo:FormGroup;
constructor(private router: Router) { }
ngOnInit() {
}
onSubmit() {
if (this.userInfo.valid) {
console.log("Form Submitted!");
}
}
public userInfo:FormGroup; - adding this in the .ts file helped

angular2: how to use input fields in sub components of forms

Look at my plunkr:
http://plnkr.co/edit/hB34VjxP98uz1iAYS7Dw?p=preview
Name is included in myform.form, but Name1 of component inner is not. How do I include Name1 in myform?
<div class="container">
<div [hidden]="submitted">
<h1>Hero Form</h1>
<form #heroForm="ngForm">
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" required
[(ngModel)]="modelname"
name="name" #name="ngModel" >
<div [hidden]="name.valid || name.pristine" class="alert alert-danger">
Name is required
</div>
<inner></inner>
</div>
</form>
{{heroForm.form.value | json}}
</div>
Template of inner.component:
<label for="name">Name1</label>
<input type="text" class="form-control" required
[(ngModel)]="modelname1"
name="name1" #name1="ngModel" >
<div [hidden]="name1.valid || name1.pristine" class="alert alert-danger">
Name1 is required
</div>
See this issue:
https://github.com/angular/angular/issues/9600
I have fixed your code to accomplish your end goal. Now both Name and Name1 are included in the form and values are coming up on the display for you
I have created a fork from your plnkr and fixed your code to support your use case. Please take a look : http://plnkr.co/edit/UHkwJ9?p=preview
inner.component.html is changed as :
<label for="name">Name1</label>
<input type="text" class="form-control" required
[(ngModel)]="modelname1" [formModel]="form" [registerModel]="name2"
name="name2" #name2="ngModel" >
<div [hidden]="name2.valid || name2.pristine" class="alert alert-danger">
Name1 is required
</div>
hero-form.component.ts is changed as :
<inner [form]="heroForm"></inner>
New Directive is added which will register a new control in the existing form reference :
import { Directive, ElementRef, Input, OnInit } from '#angular/core';
import { NgModel, NgForm } from '#angular/forms';
#Directive({
selector: '[formModel]'
})
export class FormModelDirective implements OnInit {
private el: HTMLInputElement;
#Input('formModel') public form: NgForm;
#Input('registerModel') public model: NgModel;
constructor(el: ElementRef) {
this.el = el.nativeElement;
}
ngOnInit() {
if (this.form && this.model) {
this.form.form.addControl(this.model.name, this.model.control);
}
}
}
Output Image :
Output of the plnkr code
Reference : plnkr.co/edit/GG2TVHHHGbAzoOP5mIRr?p=preview

Angular 2.0 and Modal Dialog

I am trying to find some examples on how to do a Confirmation modal dialog in Angular 2.0. I have been using Bootstrap dialog for Angular 1.0 and unable to find any examples in the web for Angular 2.0. I also checked angular 2.0 docs with no luck.
Is there a way to use the Bootstrap dialog with Angular 2.0?
Angular 2 and up
Bootstrap css (animation is preserved)
NO JQuery
NO bootstrap.js
Supports custom modal content (just like accepted answer)
Recently added support for multiple modals on top of each other.
`
#Component({
selector: 'app-component',
template: `
<button type="button" (click)="modal.show()">test</button>
<app-modal #modal>
<div class="app-modal-header">
header
</div>
<div class="app-modal-body">
Whatever content you like, form fields, anything
</div>
<div class="app-modal-footer">
<button type="button" class="btn btn-default" (click)="modal.hide()">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</app-modal>
`
})
export class AppComponent {
}
#Component({
selector: 'app-modal',
template: `
<div (click)="onContainerClicked($event)" class="modal fade" tabindex="-1" [ngClass]="{'in': visibleAnimate}"
[ngStyle]="{'display': visible ? 'block' : 'none', 'opacity': visibleAnimate ? 1 : 0}">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<ng-content select=".app-modal-header"></ng-content>
</div>
<div class="modal-body">
<ng-content select=".app-modal-body"></ng-content>
</div>
<div class="modal-footer">
<ng-content select=".app-modal-footer"></ng-content>
</div>
</div>
</div>
</div>
`
})
export class ModalComponent {
public visible = false;
public visibleAnimate = false;
public show(): void {
this.visible = true;
setTimeout(() => this.visibleAnimate = true, 100);
}
public hide(): void {
this.visibleAnimate = false;
setTimeout(() => this.visible = false, 300);
}
public onContainerClicked(event: MouseEvent): void {
if ((<HTMLElement>event.target).classList.contains('modal')) {
this.hide();
}
}
}
To show the backdrop, you'll need something like this CSS:
.modal {
background: rgba(0,0,0,0.6);
}
The example now allows for multiple modals at the same time. (see the onContainerClicked() method).
For Bootstrap 4 css users, you need to make 1 minor change (because a css class name was updated from Bootstrap 3). This line:
[ngClass]="{'in': visibleAnimate}" should be changed to:
[ngClass]="{'show': visibleAnimate}"
To demonstrate, here is a plunkr
Here's a pretty decent example of how you can use the Bootstrap modal within an Angular2 app on GitHub.
The gist of it is that you can wrap the bootstrap html and jquery initialization in a component. I've created a reusable modal component that allows you to trigger an open using a template variable.
<button type="button" class="btn btn-default" (click)="modal.open()">Open me!</button>
<modal #modal>
<modal-header [show-close]="true">
<h4 class="modal-title">I'm a modal!</h4>
</modal-header>
<modal-body>
Hello World!
</modal-body>
<modal-footer [show-default-buttons]="true"></modal-footer>
</modal>
You just need to install the npm package and register the modal module in your app module:
import { Ng2Bs3ModalModule } from 'ng2-bs3-modal/ng2-bs3-modal';
#NgModule({
imports: [Ng2Bs3ModalModule]
})
export class MyAppModule {}
This is a simple approach that does not depend on jquery or any other library except Angular 2.
The component below (errorMessage.ts) can be used as a child view of any other component. It is simply a bootstrap modal that is always open or shown. It's visibility is governed by the ngIf statement.
errorMessage.ts
import { Component } from '#angular/core';
#Component({
selector: 'app-error-message',
templateUrl: './app/common/errorMessage.html',
})
export class ErrorMessage
{
private ErrorMsg: string;
public ErrorMessageIsVisible: boolean;
showErrorMessage(msg: string)
{
this.ErrorMsg = msg;
this.ErrorMessageIsVisible = true;
}
hideErrorMsg()
{
this.ErrorMessageIsVisible = false;
}
}
errorMessage.html
<div *ngIf="ErrorMessageIsVisible" class="modal fade show in danger" id="myModal" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Error</h4>
</div>
<div class="modal-body">
<p>{{ErrorMsg}}</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" (click)="hideErrorMsg()">Close</button>
</div>
</div>
</div>
</div>
This is an example parent control (some non-relevant code has been omitted for brevity):
parent.ts
import { Component, ViewChild } from '#angular/core';
import { NgForm } from '#angular/common';
import {Router, RouteSegment, OnActivate, ROUTER_DIRECTIVES } from '#angular/router';
import { OnInit } from '#angular/core';
import { Observable } from 'rxjs/Observable';
#Component({
selector: 'app-application-detail',
templateUrl: './app/permissions/applicationDetail.html',
directives: [ROUTER_DIRECTIVES, ErrorMessage] // Note ErrorMessage is a directive
})
export class ApplicationDetail implements OnActivate
{
#ViewChild(ErrorMessage) errorMsg: ErrorMessage; // ErrorMessage is a ViewChild
// yada yada
onSubmit()
{
let result = this.permissionsService.SaveApplication(this.Application).subscribe(x =>
{
x.Error = true;
x.Message = "This is a dummy error message";
if (x.Error) {
this.errorMsg.showErrorMessage(x.Message);
}
else {
this.router.navigate(['/applicationsIndex']);
}
});
}
}
parent.html
<app-error-message></app-error-message>
// your html...
Now available as a NPM package
angular-custom-modal
#Stephen Paul continuation...
Angular 2 and up Bootstrap css (animation is preserved)
NO JQuery
NO bootstrap.js
Supports custom modal content
Support for multiple modals on top of each
other.
Moduralized
Disable scroll when modal is open
Modal gets destroyed when navigating away.
Lazy content initialization, which gets ngOnDestroy(ed) when the modal is exited.
Parent scrolling disabled when modal is visible
Lazy content initialization
Why?
In some cases you might not want to modal to retain its status after having been closed, but rather restored to the initial state.
Original modal issue
Passing the content straightforward into the view actually generates initializes it even before the modal gets it. The modal doesn't have a way to kill such content even if using a *ngIf wrapper.
Solution
ng-template. ng-template doesn't render until ordered to do so.
my-component.module.ts
...
imports: [
...
ModalModule
]
my-component.ts
<button (click)="reuseModal.open()">Open</button>
<app-modal #reuseModal>
<ng-template #header></ng-template>
<ng-template #body>
<app-my-body-component>
<!-- This component will be created only when modal is visible and will be destroyed when it's not. -->
</app-my-body-content>
<ng-template #footer></ng-template>
</app-modal>
modal.component.ts
export class ModalComponent ... {
#ContentChild('header') header: TemplateRef<any>;
#ContentChild('body') body: TemplateRef<any>;
#ContentChild('footer') footer: TemplateRef<any>;
...
}
modal.component.html
<div ... *ngIf="visible">
...
<div class="modal-body">
ng-container *ngTemplateOutlet="body"></ng-container>
</div>
References
I have to say that it wouldn't have been possible without the excellent official and community documentation around the net. It might help some of you too to understand better how ng-template, *ngTemplateOutlet and #ContentChild work.
https://angular.io/api/common/NgTemplateOutlet
https://blog.angular-university.io/angular-ng-template-ng-container-ngtemplateoutlet/
https://medium.com/claritydesignsystem/ng-content-the-hidden-docs-96a29d70d11b
https://netbasal.com/understanding-viewchildren-contentchildren-and-querylist-in-angular-896b0c689f6e
https://netbasal.com/understanding-viewchildren-contentchildren-and-querylist-in-angular-896b0c689f6e
Full copy-paste solution
modal.component.html
<div
(click)="onContainerClicked($event)"
class="modal fade"
tabindex="-1"
[ngClass]="{'in': visibleAnimate}"
[ngStyle]="{'display': visible ? 'block' : 'none', 'opacity': visibleAnimate ? 1 : 0}"
*ngIf="visible">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<ng-container *ngTemplateOutlet="header"></ng-container>
<button class="close" data-dismiss="modal" type="button" aria-label="Close" (click)="close()">×</button>
</div>
<div class="modal-body">
<ng-container *ngTemplateOutlet="body"></ng-container>
</div>
<div class="modal-footer">
<ng-container *ngTemplateOutlet="footer"></ng-container>
</div>
</div>
</div>
</div>
modal.component.ts
/**
* #Stephen Paul https://stackoverflow.com/a/40144809/2013580
* #zurfyx https://stackoverflow.com/a/46949848/2013580
*/
import { Component, OnDestroy, ContentChild, TemplateRef } from '#angular/core';
#Component({
selector: 'app-modal',
templateUrl: 'modal.component.html',
styleUrls: ['modal.component.scss'],
})
export class ModalComponent implements OnDestroy {
#ContentChild('header') header: TemplateRef<any>;
#ContentChild('body') body: TemplateRef<any>;
#ContentChild('footer') footer: TemplateRef<any>;
public visible = false;
public visibleAnimate = false;
ngOnDestroy() {
// Prevent modal from not executing its closing actions if the user navigated away (for example,
// through a link).
this.close();
}
open(): void {
document.body.style.overflow = 'hidden';
this.visible = true;
setTimeout(() => this.visibleAnimate = true, 200);
}
close(): void {
document.body.style.overflow = 'auto';
this.visibleAnimate = false;
setTimeout(() => this.visible = false, 100);
}
onContainerClicked(event: MouseEvent): void {
if ((<HTMLElement>event.target).classList.contains('modal')) {
this.close();
}
}
}
modal.module.ts
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
import { ModalComponent } from './modal.component';
#NgModule({
imports: [
CommonModule,
],
exports: [ModalComponent],
declarations: [ModalComponent],
providers: [],
})
export class ModalModule { }
I use ngx-bootstrap for my project.
You can find the demo here
The github is here
How to use:
Install ngx-bootstrap
Import to your module
// RECOMMENDED (doesn't work with system.js)
import { ModalModule } from 'ngx-bootstrap/modal';
// or
import { ModalModule } from 'ngx-bootstrap';
#NgModule({
imports: [ModalModule.forRoot(),...]
})
export class AppModule(){}
Simple static modal
<button type="button" class="btn btn-primary" (click)="staticModal.show()">Static modal</button>
<div class="modal fade" bsModal #staticModal="bs-modal" [config]="{backdrop: 'static'}"
tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title pull-left">Static modal</h4>
<button type="button" class="close pull-right" aria-label="Close" (click)="staticModal.hide()">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
This is static modal, backdrop click will not close it.
Click <b>×</b> to close modal.
</div>
</div>
</div>
</div>
Here is my full implementation of modal bootstrap angular2 component:
I assume that in your main index.html file (with <html> and <body> tags) at the bottom of <body> tag you have:
<script src="assets/js/jquery-2.1.1.js"></script>
<script src="assets/js/bootstrap.min.js"></script>
modal.component.ts:
import { Component, Input, Output, ElementRef, EventEmitter, AfterViewInit } from '#angular/core';
declare var $: any;// this is very importnant (to work this line: this.modalEl.modal('show')) - don't do this (becouse this owerride jQuery which was changed by bootstrap, included in main html-body template): let $ = require('../../../../../node_modules/jquery/dist/jquery.min.js');
#Component({
selector: 'modal',
templateUrl: './modal.html',
})
export class Modal implements AfterViewInit {
#Input() title:string;
#Input() showClose:boolean = true;
#Output() onClose: EventEmitter<any> = new EventEmitter();
modalEl = null;
id: string = uniqueId('modal_');
constructor(private _rootNode: ElementRef) {}
open() {
this.modalEl.modal('show');
}
close() {
this.modalEl.modal('hide');
}
closeInternal() { // close modal when click on times button in up-right corner
this.onClose.next(null); // emit event
this.close();
}
ngAfterViewInit() {
this.modalEl = $(this._rootNode.nativeElement).find('div.modal');
}
has(selector) {
return $(this._rootNode.nativeElement).find(selector).length;
}
}
let modal_id: number = 0;
export function uniqueId(prefix: string): string {
return prefix + ++modal_id;
}
modal.html:
<div class="modal inmodal fade" id="{{modal_id}}" tabindex="-1" role="dialog" aria-hidden="true" #thisModal>
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header" [ngClass]="{'hide': !(has('mhead') || title) }">
<button *ngIf="showClose" type="button" class="close" (click)="closeInternal()"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<ng-content select="mhead"></ng-content>
<h4 *ngIf='title' class="modal-title">{{ title }}</h4>
</div>
<div class="modal-body">
<ng-content></ng-content>
</div>
<div class="modal-footer" [ngClass]="{'hide': !has('mfoot') }" >
<ng-content select="mfoot"></ng-content>
</div>
</div>
</div>
</div>
And example of usage in client Editor component:
client-edit-component.ts:
import { Component } from '#angular/core';
import { ClientService } from './client.service';
import { Modal } from '../common';
#Component({
selector: 'client-edit',
directives: [ Modal ],
templateUrl: './client-edit.html',
providers: [ ClientService ]
})
export class ClientEdit {
_modal = null;
constructor(private _ClientService: ClientService) {}
bindModal(modal) {this._modal=modal;}
open(client) {
this._modal.open();
console.log({client});
}
close() {
this._modal.close();
}
}
client-edit.html:
<modal [title]='"Some standard title"' [showClose]='true' (onClose)="close()" #editModal>{{ bindModal(editModal) }}
<mhead>Som non-standart title</mhead>
Some contents
<mfoot><button calss='btn' (click)="close()">Close</button></mfoot>
</modal>
Ofcourse title, showClose, <mhead> and <mfoot> ar optional parameters/tags.
Check ASUI dialog which create at runtime. There is no need of hide and show logic. Simply service will create a component at runtime using AOT
ASUI NPM
try to use ng-window, it's allow developer to open and full control multiple windows in single page applications in simple way, No Jquery, No Bootstrap.
Avilable Configration
Maxmize window
Minimize window
Custom size,
Custom posation
the window is dragable
Block parent window or not
Center the window or not
Pass values to chield window
Pass values from chield window to parent window
Listening to closing chield window in parent window
Listen to resize event with your custom listener
Open with maximum size or not
Enable and disable window resizing
Enable and disable maximization
Enable and disable minimization
Angular 7 + NgBootstrap
A simple way of opening modal from main component and passing result back to it. is what I wanted. I created a step-by-step tutorial which includes creating a new project from scratch, installing ngbootstrap and creation of Modal. You can either clone it or follow the guide.
Hope this helps new to Angular.!
https://github.com/wkaczurba/modal-demo
Details:
modal-simple template (modal-simple.component.html):
<ng-template #content let-modal>
<div class="modal-header">
<h4 class="modal-title" id="modal-basic-title">Are you sure?</h4>
<button type="button" class="close" aria-label="Close" (click)="modal.dismiss('Cross click')">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<p>You have not finished reading my code. Are you sure you want to close?</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-outline-dark" (click)="modal.close('yes')">Yes</button>
<button type="button" class="btn btn-outline-dark" (click)="modal.close('no')">No</button>
</div>
</ng-template>
The modal-simple.component.ts:
import { Component, OnInit, ViewChild, Output, EventEmitter } from '#angular/core';
import { NgbModal } from '#ng-bootstrap/ng-bootstrap';
#Component({
selector: 'app-modal-simple',
templateUrl: './modal-simple.component.html',
styleUrls: ['./modal-simple.component.css']
})
export class ModalSimpleComponent implements OnInit {
#ViewChild('content') content;
#Output() result : EventEmitter<string> = new EventEmitter();
constructor(private modalService : NgbModal) { }
open() {
this.modalService.open(this.content, {ariaLabelledBy: 'modal-simple-title'})
.result.then((result) => { console.log(result as string); this.result.emit(result) },
(reason) => { console.log(reason as string); this.result.emit(reason) })
}
ngOnInit() {
}
}
Demo of it (app.component.html) - simple way of dealing with return event:
<app-modal-simple #mymodal (result)="onModalClose($event)"></app-modal-simple>
<button (click)="mymodal.open()">Open modal</button>
<p>
Result is {{ modalCloseResult }}
</p>
app.component.ts - onModalClosed is executed once modal is closed:
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
modalCloseResult : string;
title = 'modal-demo';
onModalClose(reason : string) {
this.modalCloseResult = reason;
}
}
Cheers