gpt4 book ai didi

angular - 捕获从 中的组件发出的事件?

转载 作者:太空狗 更新时间:2023-10-29 17:20:19 25 4
gpt4 key购买 nike

我有一个使用 <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永远不会收到事件。

例如:

即将短缺。我做错了什么?


更新:

@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');
}

我可以记录点击事件,所以它正在发生,但主机监听器失败了。想法?


更新2

我放弃了这种支持共享服务的方法,但我遇到了 .next() 的问题未向订户提供值(value):Subscriber doesn't receive value from .next()

最佳答案

您可以使用 @ContentChild() 获取登录模式的实例并手动订阅打开事件

@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 {
@ContentChild(LoginModalComponent)
loginModal: LoginModalComponent;

ngAfterViewInit() {
this.loginModal.open.subscribe((event) => {
//Handel event here
});
}
}

关于angular - 捕获从 <ng-content> 中的组件发出的事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41858516/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com