Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular TemplateRef Issue

I have to place all the ngx-bootstrap modals in a single component.html so that I can access any modal from anywhere.

I have tried the below code in

header.componentn.html
<button (click)="Login(loginModal)">Login</button>

header.cmponent.ts
@Input() myModal: AppModalsComponent;
bsModalRef: BsModalRef;
Login(template:TemplateRef<any>) {
    this.myModal.openModal(template);
}

app-modals.component.html
<ng-template #loginModal>
    <div class="modal-body">Login Here</div>
 </ng-template>

app-modals.component.ts
openModal(template: TemplateRef<any>) {
    this.modalRef = this.modalService.show(template, this.config);
}

Complete code at StackBlitz.

I'm pasing a template Reference object from HTML. It is getting undefined in ts. I think this is bexause the corresponding ng-template is not present in same HTML. How to reslove this?

like image 426
Bhavani Prasad Avatar asked Jun 12 '26 14:06

Bhavani Prasad


1 Answers

According to the documentation you call show() on the modal service and

Pass a TemplateRef or a component as a first argument and config as a second (optionally).

To make sharing these modals easier I would just make each modal it's own component. You will need to make sure you declare it as an entryComponent in the app.module.

Then in whichever component needs to open the modal you can just inject the modal service and then pass the ModalComponent you want it to create.

modal.component.ts

@Component({
  selector: 'app-modal',
  template: '<div class="modal-body">Login Here</div>'
})
export class ModalComponent {}

some.componet.ts

@Component({
  selector: 'app-some',
  template: '<button (click)="openModal">Open the modal</button>'
})
export class SomeComponent {
  constructor(public modalService: BsModalService) { }

  openModal() {
    this.modalService.show(ModalComponent);
  }
}

Stackblitz

like image 149
Teddy Sterne Avatar answered Jun 15 '26 04:06

Teddy Sterne



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!