Open modal dialog in function in Angular 4

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

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

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

      

But I want to open modal from function to ngOnInit

component .ts.

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

+3


source to share


1 answer


Angular powered Bootstrap. can help you here.

In your component, you have to import NgbModal

and insert it into 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 text with the message "text". But I think you can add a more complex post. You can also put HTML in your component view and use it.

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

      



Further inside your method you can add a link to this template

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

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

      

The content <ng-template #wizard>

will now be displayed inside the modal file.

You can specify more detailed information using an object NgbModalOptions

and specify it when calling the method open(ref, options)

.

+1


source







All Articles