我有一个使用< 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()
我最终放弃了事件驱动的方法,而是选择了共享服务类.
原文链接:https://www.f2er.com/angularjs/141189.html