首页 > 解决方案 > 指令中的 EventEmitter 不在 Parent 中处理

问题描述

我创建了一个指令,根据用户声明显示或隐藏组件。

is-allowed.directive.ts

import { Directive, TemplateRef, ViewContainerRef, Input, Output, EventEmitter } from '@angular/core';
import { SecurityService } from 'app/_security/security.service';

@Directive({
  selector: '[appIsAllowed]'
})
export class IsAllowedDirective {

  @Output() isReady = new EventEmitter<boolean>();

  constructor(
    private templateRef: TemplateRef<any>,
    private viewContainer: ViewContainerRef,
    private ss: SecurityService,
  ) { }

  @Input('appIsAllowed') set isAllowed(claimType: any) {
    if (this.ss.hasClaim(claimType)) {
      this.viewContainer.createEmbeddedView(this.templateRef);
      this.notAllowed(false);
    } else {
      this.notAllowed(false);
      this.viewContainer.clear();
    }
  }

  notAllowed(isAllowed: boolean) {
    debugger;
    this.isReady.emit(isAllowed);
  }
}

然后我有2个组件。1 是管理模板组件,另一个是示例组件。

admin-template.component.html

<ng-container *ngIf="sampleToUpdate">
  <app-sample *appIsAllowed="'Admin'" (isReady)="notifyIfAllowed($event)"  [sampleData]="sampleToUpdate"></app-sample>
</ng-container>

admin-template.component.ts

notifyIfAllowed($event: boolean) {
    debugger;
    if (!$event) {
      this.toastr.error('You are not allowed to do this operation', 'Unauthorized', {
        closeButton: true,
        progressBar: true,
        timeOut: 3000
      });
    }
  }

样本.component.ts

 @Input() sampleData: SampleData;

  constructor() { }

  ngOnInit(): void {
    console.log(this.sampleData);
  }

一切似乎都按指令中的预期工作,但不知何故,父组件notifyIfAllowed()没有被调用,因为它没有进入断点。我想要实现的是;什么时候<app-sample>无法显示,因为claimsdirective我需要一个 toastr 来通知用户。

标签: angularangular2-directives

解决方案


推荐阅读