how to open ng-template modal from component?

Solution 1:

Get the reference of the template in typescript using @ViewChild() decorator and use ngAfterViewInit() hook to open the modal..

@ViewChild('template') templateRef: TemplateRef<any>;


ngAfterViewInit() {
  const user = {
      id: 10
    };
  this.modalRef = this.modalService.show(this.templateRef, {
    initialState : user
  });
}

https://stackblitz.com/edit/angular-modal-bootstap-pay2ua?file=app%2Fapp.component.ts

Edit

I just noticed that we would be getting an ExpressionChangedAfterItHasBeenCheckedError if we show it in ngAfterViewInit() hook, to fix that wrap opening the modal in a setTimeuut()

  setTimeout(() => {
    this.modalRef = this.modalService.show(this.templateRef, {
      initialState : user
   })
  })

https://stackblitz.com/edit/angular-modal-bootstap-pr377t?file=app/app.component.ts

Solution 2:

You can use ViewChild decorator to get the reference and to load initially use AfterViewInit hook which called after Angular has fully initialized a component's view.

import { Component,TemplateRef, OnInit,ViewChild,ElementRef, AfterViewInit  } from '@angular/core';

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


  ngAfterViewInit() {
    const user = {
        id: 10
      };
      this.modalRef = this.modalService.show(this.template, {
      initialState : user
    });
  }

}

Demo