Angular 2 eventEmitter 不工作

Angular 2 eventEmitter dosen't work

我需要做一些简单的事情,我想在单击帮助图标时显示一个对话框。

我有一个父组件:

@Component({
  selector: 'app-quotation',
  templateUrl: './quotation.component.html'
})
export class QuotationComponent implements OnInit {

  public quotation: any = {};
  public device: string;
  public isDataAvailable = false;

  @Output() showPopin: EventEmitter<string> = new EventEmitter<string>();

  constructor(private quotationService: QuotationService,
              private httpErrors: HttpErrorsService,
              private popinService: PopinService) {}

  moreInfo(content: string) {
      console.log('here');
    this.showPopin.emit('bla');
  }
}

还有他的html:

<ul>
    <li *ngFor="let item of quotation.HH_Summary_TariffPageDisplay[0].content">
        <label></label>
        <i class="quotation-popin" (click)="moreInfo()"></i>
        <div class="separator"></div>
    </li>
</ul>

我的 popin 组件:

@Component({
  selector: 'app-popin',
  templateUrl: './popin.component.html',
  styleUrls: ['./popin.component.scss']
})
export class PopinComponent implements OnInit {

  public popinTitle: string;
  public popinContent: string;
  public hidden: boolean = true;

  constructor() { }

  openPopin(event):void {
    console.log("here");
    this.hidden = false;
  }

}

他的HTML:

<div class="card-block popin-container" (showPopin)="openPopin($event)" *ngIf="!hidden">
  <div class="card">
    <div class="popin-title">
      {{ popinTitle }}
      <i class="icon icon-azf-cancel"></i>
    </div>
    <div class="popin-content">
      {{ popinContent }}
    </div>
  </div>
</div>

我的父组件加载在路由器插座中,我的 popin 加载在与路由器插座相同的级别,如下所示:

<app-nav-bar></app-nav-bar>
<app-breadcrumb></app-breadcrumb>
<div class="container">
  <router-outlet></router-outlet>
</div>

<app-popin></app-popin>

我的问题是 eventEmitter 不工作,我不知道为什么,有人可以解释我吗?

谢谢,

问候

是因为你用错了。

在您的 popin 组件中,您只需调用函数并执行日志,然后将变量设置为 false。

而且我在任何地方都看不到您使用 app-quotation 选择器,所以您并没有真正使用它,是吗?

您似乎正在将输出发送到 child 组件 (popin)。理想情况下,如果您给出的输出意味着它应该从 child 到 parent 以及从 parent 到 child,那么它就是输入。

EventEmitter 仅适用于直接父子组件关系。您与此处描述的组件没有这种关系。

在父子关系中,我们会在父模板中看到子组件元素。我们在您的示例中看不到这一点。

你有两个选择:

  1. 重构以使用父子关系
  2. 使用通信服务

如果您选择选项 2,该服务应该只包含一个组件接下来调用的可观察对象,而另一个组件订阅。

@Injectable()
export class PopinService {
  showPopin = new ReplaySubject<string>(1); 
}

在 QuotationComponent 中注入并修改 moreInfo

  moreInfo(content: string): void {
    this.popinService.showPopin.next('bla' + content);
  }

在 PopinComponent 中注入 popinService 并添加以下内容:

ngOnInit() {

  this.popinService.showPopin.subscribe(content => {
    this.hidden = false;
    this.popinContent = content;
  });

}