【问题标题】:ngFor with ngBootstrap NgbModal Open - Angular BootstrapngFor 与 ngBootstrap NgbModal 打开 - Angular Bootstrap
【发布时间】:2021-11-21 00:15:44
【问题描述】:

*ngFor 循环内呈现的项目中调用 NgbModal open() 时遇到问题。

我有一个要显示的项目列表。在上述项目的click 上,我希望打开一个模式以提示用户提供一些其他信息。

单击项目时,我可以看到元素通过 DevTools 添加到 DOM,但模式没有添加 show 类。应该呈现为模态内容的组件也未正确初始化。如果我手动添加show 类,我可以看到模态的内容,但组件不能正常工作。

重要的是要注意,为了测试,我添加了一个订阅点击事件的按钮,它将一个假项目传递给相同的函数setSelected()。这种打开模式的方法没有问题。该问题仅在*ngFor 内出现。

我有一个console.logConnectionModalComponent(作为模态的内容传递)构造函数中,另一个是ngAfterViewInit。当通过*ngFor 之外的按钮激活模式时,我在控制台中看到了两个日志语句,但是当从*ngFor 中激活模式时,我只看到构造函数的日志语句,而不是后者。

我正在使用@angular/core@12.1.2 & @ng-bootstrap/ng-bootstrap@10.0.0

testComponent.html.ts - 具有 *ngFor 的组件

        <div>
          <div
            *ngFor="let item of items"
            (click)="setSelected(item)"
          >
            <span class="full-height">
              <div class="card-body">
                <div class="card-title">
                  {{ item.nickname }}
                </div>
              </div>
            </span>
          </div>
        </div>

testComponent.component.ts - 从 HTML 模板调用的函数。

  public setSelected(item: ItemViewModel): void {
    this.testAlertService.open();
  }

testAlert.service.ts - 从组件调用以打开 NgbModal 的服务。

import { Injectable } from '@angular/core';
import { NgbModal, ModalDismissReasons } from '@ng-bootstrap/ng-bootstrap';

import { ConnectionModalComponent } from '../../components/shared';

@Injectable()
export class TestAlertService {
  constructor(private modalService: NgbModal) {}

  open() {
    this.modalService.open(ConnectionModalComponent, { ariaLabelledBy: 'modal-basic-title' }).result.then(
      (result) => {
        console.log(`Closed with: ${result}`);
      },
      (reason) => {
        console.log(`Dismissed ${this.getDismissReason(reason)}`);
      }
    );
  }

  private getDismissReason(reason: any): string {
    if (reason === ModalDismissReasons.ESC) {
      return 'by pressing ESC';
    } else if (reason === ModalDismissReasons.BACKDROP_CLICK) {
      return 'by clicking on a backdrop';
    } else {
      return `with: ${reason}`;
    }
  }
}

【问题讨论】:

    标签: angular typescript ngfor ng-bootstrap ng-bootstrap-modal


    【解决方案1】:

    我能够解决问题。

    testComponent.component.ts 内部,我正在推送到items 数组,我在ChangeDetectorRef 类上使用了detectChanges() 方法。

    通过简单地包装数组突变以使用NgZonerun() 解决了我所有的问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-09-23
      • 2021-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-25
      • 1970-01-01
      相关资源
      最近更新 更多