加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angular – 捕获内部组件发出的事件?

发布时间:2020-12-17 08:48:16 所属栏目:安全 来源:网络整理
导读:我有一个使用 ng-content的自定义模态组件.转换内容: @Component({ selector: 'modal-container',template: ` div [class]="css" div [attr.id]="id" class="reveal" (open)="openModal()" ng-content/ng-content /div /div `})export class ModalContainer
我有一个使用< ng-content>的自定义模态组件.转换内容:
@Component({
  selector: 'modal-container',template: `
    <div [class]="css">
      <div [attr.id]="id" class="reveal" (open)="openModal()">
        <ng-content></ng-content>
      </div>
    </div>
  `
})
export class ModalContainerComponent {
    . . .
}

在< ng-content>的内容中我有一个发出open事件的组件:

@Component({
  selector: 'login-modal',template: `
    <modal-container [id]="'login-modal'">
      <section>...</section>
    </modal-container>
  `,})
export class LoginModalComponent implements OnInit {

    @Output()
    open = new EventEmitter();

    ngOnInit(): void {
        // Here I am checking an ngrx store with code that is not included
        if (state.openLoginModal) {
          this.open.emit();
        }
    }

}

但是,ModalContainerComponent永远不会收到该事件.

例如:

> How to observe input element changes in ng-content
> Angular 2: capture events from ng-content

很快就会出现.我究竟做错了什么?

更新:

由于@Output事件没有冒泡,我决定使用自定义指令来发出事件:

import { Directive,ElementRef,Renderer } from '@angular/core';


@Directive({
  selector: '[open-modal]',host: { '(click)': 'openModal()' }
})
export class OpenModalDirective {

  constructor(
    private elementRef: ElementRef,private renderer: Renderer
  ) {}

  openModal(): void {
    this.renderer.invokeElementMethod(this.elementRef.nativeElement,'dispatchEvent',[new CustomEvent('open-modal-container',{ bubbles: true })]);
  }

}

使用:in Angular2 how to know when ANY form input field lost focus作为例子.

但是,我仍然无法在ModalContainerComponent中获取自定义事件:

@HostListener('open-modal-container')
openModalContainer(): void {
  console.log('openModal() was invoked');
}

我可以记录click事件,这样就发生了,但是主机监听器失败了.思考?

更新2

我放弃了这种方法,转而使用共享服务,但是我遇到了一个问题,即.next()没有为订阅者提供价值:Subscriber doesn’t receive value from .next()

我最终放弃了事件驱动的方法,而是选择了共享服务类.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读