【问题标题】:How to display modal Component from another Component in Angular 11如何在Angular 11中显示来自另一个组件的模态组件
【发布时间】:2022-01-15 19:56:04
【问题描述】:

我正在尝试显示来自另一个主组件的模态组件,但在呈现父组件时我收到来自模态组件的 404 错误。 我认为是因为试图在加载之前从主组件访问模态组件。

我在 NgModule 声明中声明了模态组件。 尝试了很多东西,但我还不能让它工作......

这是我的父组件portfolio.component.html

`  <button class="btn btn-outline-primary"(click)="viewModal()">
      View portfolio n. 1
   </button>`

然后在portfolio.component.ts中

import { PortfolioService } from './portfolio.service';
@Component({
  selector: 'app-portfolio',
  templateUrl: './portfolio.component.html',
  styleUrls: ['./portfolio.component.scss'],
})
export class PortfolioComponent implements AfterViewInit {
   //declare service to render the data from another component
   constructor(private portfolioService: PortfolioService) {}
    
ngAfterViewInit() {}

viewModal() {
    this.portfolioService.displayPortfolio();
  }
}

终于在portfolio.service.ts上

import { Injectable } from '@angular/core';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { ExamplePortfolioComponent } from './portfolios-list/example-portfolio.template.component';
@Injectable()
export class PortfolioService {
  examplePortfolio: ExamplePortfolioComponent;
  modalService: NgbModal;

  constructor() {}
  // here I'm trying to display the modal, but it doesn't work
  displayPortfolio() {
    this.modalService.open(this.examplePortfolio, {
      windowClass: 'dark-modal',
    });
  }
}

如何正确显示来自另一个主要组件的模态组件?

【问题讨论】:

  • 可以试试直接把类名传入portfolio.service.ts中的方法吗?像这样:this.modelService.open(ExamplePortfolioComponent, { ...

标签: angular typescript angular-material angular-services angular-components


【解决方案1】:

仅在服务中声明的属性不会注入其中。我认为您应该通过构造函数注入 ngmodal 服务,而不是声明为属性

constructor(modalService: NgbModal) {}

当您尝试打开模式而不是尝试传递对对象的引用时,您还应该直接传递 ExamplePortfolioComponent,我认为它接收一种组件类型而不是对其实例的引用。 还要检查你是否将你的服务作为提供者注入到任何模块中,我认为你应该用这样的范围声明

@Injectable({
    providedIn: 'root'
})
export class PortfolioService

【讨论】:

  • 好的,我听从了您的建议并成功了。我还必须在模态组件构造函数上添加公共 NgbActiveModal。非常感谢! (:
  • 嗨,很高兴知道。在这种情况下,您可以将我的答案标记为您问题的答案。谢谢
猜你喜欢
  • 2017-09-02
  • 2020-04-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-10
  • 2019-03-10
相关资源
最近更新 更多