【问题标题】:Bootstrap Modal popup component not working on click of angular formly elementBootstrap Modal弹出组件在单击角度形式元素时不起作用
【发布时间】:2020-12-23 13:31:03
【问题描述】:

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

我关注的demo链接:Bootstrap modal Stackblitz Demo

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

使用 openModal() 函数单击徽标时出现的错误是未定义的对象。

如何在使用角度形式时纠正这个问题?

下面是sn-p的代码:

多选表单组件

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

【问题讨论】:

  • 你是如何得到你在 stackblitz 中提到的错误的?
  • 我单击 中的多选行的图标,然后我得到错误,

标签: javascript angular ngx-formly


【解决方案1】:

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

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

这样可以保持你想要的关闭,你可以阅读更多关于它here

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

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

entryComponents: [CalenderComponent]

这是一个分叉的工作stackblitz

【讨论】:

  • 以最好的方式描述,感谢提供的支持和解决方案,我得到了使用闭包和使用 entryComponents 的概念。请对问题进行投票以获得更好的影响力。干杯!
  • Moshezauros 你能帮我解决其中一个要求吗:答案的最后评论:stackoverflow.com/questions/65284562/…
猜你喜欢
  • 1970-01-01
  • 2018-12-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-15
  • 2015-09-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多