-1

$('#myModal').modal('show'); $('#myModal').modal('hide'); This is the way we follow to open a modal from js file.I am now working in angular 5. How to open modal from .ts file? To be very clear how to talk with DOM from the .ts file in angular 5,like using document.getElementById("demo") we do in js file.

<div class=" col-sm-6 clearPadding">
<div class="addBottomPadding">
  <h2>Events</h2>
</div>
<div class="addTopPadding" *ngIf="flagEvent">
  <canvas baseChart [data]="eventPieChartData" [labels]="pieChartLabels" [chartType]="pieChartType" (chartHover)="chartHovered($event)"
    (chartClick)="eventChartClicked($event)" data-toggle="modal" data-target="***********">
  </canvas>
</div>

<div class="col-sm-6 clearPadding">
<div class="addBottomPadding">   
  <h2>Registrants</h2>

</div>
<div class="addTopPadding" *ngIf="flagUser">
  <canvas baseChart [data]="usersPieChartData" [labels]="pieChartLabels" [chartType]="pieChartType" (chartHover)="chartHovered($event)"
    (chartClick)="regChartClicked($event)" data-toggle="modal" data-target="**************">
  </canvas>
</div>

This is my code. I have written ***** in place of modal target because , the function call (chartClick)="eventChartClicked($event) has 2 conditions. For each condition i wnt to open a modal from my typescript file.Here i cant use button also.

Abhiz
  • 970
  • 1
  • 16
  • 36

2 Answers2

2

The code which working in .js file should work in .ts file, so if you are using document.getElementById("demo") in your JS file then this peice of code will also work in typescript file.

For example

<button id="demo" [hidden]="true" data-toggle="modal" data-target="#myModal">Open Modal</button>


document.getElementById("demo").click();

You can refer to this question -

Pardeep Jain
  • 84,110
  • 37
  • 165
  • 215
  • Thank you.my goal is a bit different. but when i write ` document.getElementById('eventModal').modal('show');` this error is thrown `Property 'modal' does not exist on type 'HTMLElement'.` – Abhiz May 16 '18 at 09:47
  • 1
    You cannot access document like that, when TypeScript is set to strict. – Tigerware Aug 01 '19 at 14:53
  • 1
    @BluE you can, but not recommended though. I understand your concern in that case you can add check `isPlatformBrowser` or you can use another way like `viewchild` may be using local variable in the template – Pardeep Jain Aug 02 '19 at 06:42
  • 1
    Actually I made a mistake here. I thought TypeScript does not allow to use document like that, bc Visual Studio Typescript would not compile. The actual problem was a missing null/undefined check or assertion for "document.getElementById("demo")" before calling a function like "click()" on it. – Tigerware Aug 02 '19 at 07:47
0

In case of angular, usually the modal is usually crafted as a separate reusable component. Please take following example of wrapping the bootstrap modal to use inside Angular4 as a component. Similar approach should work for Angular5 too.

modal.component.html

<!-- Modal -->
<div class="modal fade" id="{{modalId}}" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" data-backdrop="static"
    data-keyboard="false">
    <div id = "setSize" class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <ng-content select="[modal-title]"></ng-content>
                <button id="{{hideId}}" type="button" class="close" data-dismiss="modal" (click)="xClicked()" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>                
            </div>
            <div class="modal-body">
                <ng-content select="[modal-body]"></ng-content>
            </div>
            <div class="modal-footer" *ngIf="options.footer">
                <ng-content select="[modal-footer]"></ng-content>
            </div>
        </div>
    </div>
</div>

modal.component.ts

import { ModalOptions } from './modal-options';
import { Component, OnInit, OnChanges, Output, EventEmitter, Input } from '@angular/core';

@Component({
  selector: 'modal-component',
  templateUrl: './modal.component.html',
  styleUrls: ['./modal.component.scss'],
  inputs: ['toggle']
})
export class ModalComponent implements OnInit {
  private toggle: EventEmitter<any>;
  @Input() options: ModalOptions = new ModalOptions();
  @Output() onModalClose = new EventEmitter<any>();

  //ADDED TO ADJUST MODAL SIZE FOR TICKER COMPONENT
  @Input() size: string;

  public showId: string;
  public hideId: string;
  public modalId: string;

  constructor() {
    this.showId = this.randomId();
    this.hideId = this.randomId();
    this.modalId = this.randomId();

  }

  ngOnInit() {
    if (this.size == 'large') {
      document.getElementById('setSize').className = "modal-dialog modal-lg"
    }
    this.toggle.subscribe(e => {
      if (e.toLowerCase() === 'show') {
        document.getElementById(this.showId).click();
      } else if (e.toLowerCase() === 'hide') {
        document.getElementById(this.hideId).click();
      }
      //document.getElementById(this.id).click();
    })
  }


  private randomId() {
    let length = 5;
    let chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    var result = '';
    for (var i = length; i > 0; --i) result += chars[Math.floor(Math.random() * chars.length)];
    return result;
  }

  xClicked() {
    this.onModalClose.emit();
  }
}

modal.option.ts (just some functionality I had to implement, not necessary)

export class ModalOptions {
    footer: boolean = true;
    topClose: boolean = false;
}

Usage,

some.component.html

<modal-component [toggle]="modal">
    <div modal-body>

    </div>
    <!--footer-->
    <div modal-footer>
    </div>
</modal-component>

some.component.ts

export class SomeComponent{
  public modal = new EventEmitter<any>();

  public show(){ this.modal.emit("show"); }

 public hide() { this.modal.emit("hide");}

}

Hope this helps.

bibek shrestha
  • 448
  • 3
  • 9