gpt4 book ai didi

javascript - 从指令发出事件时, Angular 事件发射器不工作

转载 作者:行者123 更新时间:2023-12-02 23:12:29 41 4
gpt4 key购买 nike

appcomp.html

`<app-child (callemit) = parentFunc($event)> </app-child>`

appcomp.ts

`

import { Component, OnInit, EventEmitter } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.comp.html'
})
export class AppComponent {
ngOnInit() {}
parentFunc(event){
console.log(event)
}
}

`

childcomp.html

<a href='' [mydirective]="val"> </a>

childcomp.ts

`

@Component({
selector: 'app-child',
templateUrl: './app.child.component.html'
})

`

mydirective.ts

`

import { Directive, ElementRef, Input, Output, HostListener, EventEmitter } from '@angular/core';

@Directive({
selector: '[myDirective]'
})
export class myAppDirective {
constructor() {}
@Input ('myDirective') val: string;
@Output() callEmit = new EventEmitter();
@HostListener('click')
onClick() {
event.preventDefault();
this.callEmit.emit({event , val});
}
}

`在上面的代码中,我尝试使用 eventemitter 从 appcomp 调用parentFunc,但无法完成这项工作。请让我知道这里出了什么问题。

最佳答案

我认为您最常在子组件上调用 callEmit

childcomp.html

<a href='' [mydirective]="val" (callEmit)="childFunc($event)"> </a>

并在子组件中发出从 appComp 调用的 CallEmit

childcomp.ts

@Output() callEmit = new EventEmitter();

childFunc(){
this.callEmit.emit();
}

最后使用

appCom.html

`<app-child (callemit) = parentFunc($event)> </app-child>`

appcom.ts

 parentFunc(event){
console.log(event)
}

https://stackblitz.com/edit/angular-exxhms

关于javascript - 从指令发出事件时, Angular 事件发射器不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57284134/

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