4

I have an angular 4 application and I want to open a modal dialog in a function.

So, I have my modal code that I can open when I click on a button :

<button class="btn btn-primary" id="test" (click)="open(addProjectForm)">test</button>

But I want to open the modal from a function in the ngOnInit of component.ts.

So, how can I open the modal inside a function and not with the click option ?

Adrien
  • 2,866
  • 4
  • 23
  • 46
  • simply call open(addProjectForm) from ngOnInit. – Fahad Nisar Jul 07 '17 at 09:38
  • But the button with `open(addProjectForm` is in modal.component.html and I want to call this in another component : timeline.component.ts. So, the name can't be find. – Adrien Jul 07 '17 at 09:41
  • so basically what you want to say is that you want to call the function defined in one component from another component right? – Fahad Nisar Jul 07 '17 at 09:42
  • Yes. I want to call the open of a modal in another component. – Adrien Jul 07 '17 at 09:54
  • 1
    Have a look at this [**answer**](https://stackoverflow.com/questions/42735858/ng2-bootstrap-show-hide-modal-as-child-component/42736058#42736058) – Aravind Jul 07 '17 at 10:37
  • Actually it does matter which kind of graphical library you use. Is it bootstrap or angular material. If it's angular, do you use "angular powered bootstrap" or "ngx-bootstrap" ? – bvdb Aug 31 '17 at 14:23

1 Answers1

2

Angular powered Bootstrap. can help you here.

In your component you have to import NgbModal and inject it in your Component, using the constructor. You can use this service to open the modal.

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

@Component({ ... })
export class MyComponent implements OnInit {

  constructor(private modalService: NgbModal)
  { 
  }

  ngOnInit() {
  }

  public show()
  {
    this.modalService.open('text');
  }
}

This will open a modal, with message "text". But I guess that you may want to add a more complicated message. You can also put HTML inside your component's view, and use that.

<ng-template #wizard>
  text
</ng-template>

Next inside your method you can add a reference to that template

@ViewChild('wizard')
public wizardRef: TemplateRef<any>;  

public show()
{
  this.modalService.open(this.wizardRef);
}

Now the content of the <ng-template #wizard> will be shown inside the modal.

You can set more details using the NgbModalOptions object, and specify it when calling the open(ref, options) method.

bvdb
  • 22,839
  • 10
  • 110
  • 123