ionic Angular 8 获取组件实例

问题描述 投票:0回答:1

在使用离子和角度创建模态后,我尝试了不同的方法来获取组件实例,但是对我来说没有任何效果。您能否帮助我理解,创建模态后如何获取组件实例引用?示例代码如下:

const modal = await this.modalController.create({
  component: MyCustomComponent,
  cssClass: "some-css-class",
  componentProps:
  {
    item: item
  },
  backdropDismiss: false
});

modal.canDismiss = async (data?: any, roleDismiss?: string) => {
  let can = false;
  return new Promise<boolean>(resolve => resolve(can));
}

例如,在 canDismiss 处理程序中,我想验证一些实际的组件实例属性,但是我似乎找不到正确的方法来执行此操作。创建模式后如何访问 MyCustomCompnent 实例?

我正在使用离子角度8,角度18.1.3

angular ionic-framework ionic5
1个回答
0
投票

创建用于模态组件和父组件之间通信的服务

export class ModalService {
  private modalInstanceSubject = new BehaviorSubject<any>(null);
  modalInstance$ = this.modalInstanceSubject.asObservable();

  setModalInstance(instance: any) {
    this.modalInstanceSubject.next(instance);
  }
}

MyCustomComponent
中,注入
ModalService
并设置组件的实例

export class MyCustomComponent implements OnInit {
  constructor(private modalService: ModalService) {}

  ngOnInit() {
    this.modalService.setModalInstance(this);
  }

  // Example property you want to access
  someProperty: boolean = false;
}

在创建模态的父组件中,注入

ModalService
并订阅 modalInstance$ 以获取模态的实例

export class ParentComponent {
  constructor(private modalController: ModalController, private modalService: ModalService) {}

  async openModal() {
    const modal = await this.modalController.create({
      component: MyCustomComponent,
      cssClass: 'some-css-class',
      componentProps: {
        item: 'some item'
      },
      backdropDismiss: false
    });

    modal.present();

    this.modalService.modalInstance$.subscribe(instance => {
      if (instance) {
        // Now you can access the instance of MyCustomComponent
        console.log(instance.someProperty);

        modal.canDismiss = async (data?: any, roleDismiss?: string) => {
          // Access the component instance properties here
          return instance.someProperty;
        };
      }
    });
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.