I am using ng2-bootstrap for the modal stuff.
I am trying to separate my modals and my other components apart. So I have the following files:
addPlaylist.modal.ts
import {Component} from '@angular/core';
import {CORE_DIRECTIVES} from '@angular/common';
import {MODAL_DIRECTVES, BS_VIEW_PROVIDERS} from 'ng2-bootstrap/ng2-bootstrap';
@Component({
selector: 'addplaylist-modal',
directives: [MODAL_DIRECTVES, CORE_DIRECTIVES],
viewProviders: [BS_VIEW_PROVIDERS],
templateUrl: 'app/channel/modals/addPlaylistModal.html'
})
export class AddPlaylistModalComponent {
constructor() {
console.log(this);
}
}
addPlaylistModal.html
<div bsModal #lgModal="bs-modal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" (click)="lgModal.hide()" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title">Large modal</h4>
</div>
<div class="modal-body">
...
</div>
</div>
</div>
</div>
In it's parent component's html I have code piece like this:
<a (click)="lgModal.show()"><span class="bigplus pull-right"></span></a>
//some other code
<addplaylist-modal></addplaylist-modal>
This is the parent component: channel.component.ts
import { AddPlaylistModalComponent } from './shared/addPlaylist.modal';
@Component({
selector: 'channel',
styleUrls: ['app/channel/channel.css'],
directives: [PlatformsComponent, PagesComponent, PlaylistComponent, VideosComponent, AddPlaylistModalComponent],
providers: [PlatformService],
templateUrl: 'app/channel/channel.html'
})
What I want to do, I want to be able to let the parent componet to access it and open the modal even if I write the (click)="lgModal.show()" at parent component.
Now if I click the <a (click)="lgModal.show()"><span class="bigplus pull-right"></span></a>
, it will say “ can not read property show of undefined"
So, how to let the parent component know that the lgModal is defined and it's in its child component.
Your solution might look something like this:
ChildComponent
@Component({
...
exportAs: 'child' <== add this line
})
export class AddPlaylistModalComponent {
@ViewChild('lgModal') lgModal; <== reference to Modal directive
show(){ <== public method
this.lgModal.show();
}
}
ParentComponent
template: `<a class="btn btn-success" (click)="c.show()">Add</a>
<addplaylist-modal #c="child"></addplaylist-modal>`
See also the completed sample here https://plnkr.co/edit/2UAB7lpqqAvchTsLwzr6?p=preview