Bootstrap Modal 弹出组件在单击 angular 元素时不起作用

问题描述

我有一个要求,其中我使用了多选的角度形式,每行也有标志。 单击此徽标时,我想加载模态弹出组件,我正在关注 Stackblitz 演示,用于在单击元素时调用 app.component 中的模态组件。

我关注的演示链接Bootstrap modal Stackblitz Demo

我正在实施的解决方法演示如下:Workaround Demo Stackblitz

我在点击带有函数 openModal() 的徽标时遇到的错误是未定义的对象。

enter image description here

如何在正式使用 angular 时纠正这个问题?

以下是代码片段:

多选表单组件

@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 其中调用了模态组件(calenderComponent)

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'
       }
  });
 },}
}

解决方法

如果您对此进行调试,您可以看到函数上下文中的 this (openModal) 是您在 field 对象中定义的 fields,即没有您注入组件的 modalService 服务,为了克服这个问题,您可以使用 lambda 表达式:

  openModal: () => {
    this.modalRef = this.modalService.show(CalenderComponent,{
      initialState: {
        title: "Modal title"
      }
    });
  }

这会根据您的需要保留闭包,您可以阅读有关它的更多信息here

解决了这个问题后,你将面临另一个问题: enter image description here

要解决此问题,您需要在应用模块文件 (CalenderComponent) 中添加 app.module.ts 作为入口组件:

entryComponents: [CalenderComponent]

这是一个分叉的工作stackblitz

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...