I have a reuquirement in which i am using a multiselect of angular formly which also has logo for each row. On click of this logo i want to load modal popup component, i am following a Stackblitz Demo for calling modal-component in app.component on click of element.
The link of demo which i followed : Bootstrap modal Stackblitz Demo
My workaround demo which i am implenenting is as follows : Workaround Demo Stackblitz
The error which i am getting on click of logo with the function openModal() is of undefined object.
How to i rectify this while working with angular formly?
Following is the snippet of the code:
multiselect formly component
@Component({
selector: 'formly-field-multiselect',
template: `<br><p-multiSelect [options]="to.options"
[formControl]="formControl"
[formlyAttributes]="field"
[showClear]="!to.required" >
<ng-template let-item pTemplate="item">
<div>{{item.label}}</div>
<div>
<i class="pi pi-check" (click)="to.openModal()"></i>
</div>
</ng-template>
</p-multiSelect>
`,
})
app.component.ts in which modal component(calenderComponent) is called
fields: FormlyFieldConfig[] = [
{
key: "select",
type: "multiselect",
templateOptions: {
multiple: false,
placeholder: "Select Option",
options: [
{ label: "Select City", value: null },
{ label: "New York", value: { id: 1, name: "New York", code: "NY" } },
{ label: "Rome", value: { id: 2, name: "Rome", code: "RM" } },
{ label: "London", value: { id: 3, name: "London", code: "LDN" } },
{
label: "Istanbul",
value: { id: 4, name: "Istanbul", code: "IST" }
},
{ label: "Paris", value: { id: 5, name: "Paris", code: "PRS" } }
],
openModal() {
this.modalRef = this.modalService.show(CalenderComponent, {
initialState: {
title: 'Modal title'
}
});
},
}
}
If you debug this, you can see that this
in the context of your function (openModal
), is the field
you defined in the fields
object, which doesnt have the modalService
service you injected to the component, to overcome this, you can use a lambda expression:
openModal: () => {
this.modalRef = this.modalService.show(CalenderComponent, {
initialState: {
title: "Modal title"
}
});
}
this keeps the closure as you wanted, you can read more about it here
After you solve that problem, you will face another one:
To overcome this, you need to add the CalenderComponent
as an entrycomponent in your app module file (app.module.ts
):
entryComponents: [CalenderComponent]
Here is a forked working stackblitz