Issue
I'm trying to assign to three variables inside of my typescript class a value onInit that comes from the html file. The problem is that the event is not getting emitted for some reason. Let me show you the interested part of the code
@Output() setTarget = new EventEmitter<any>();
/** Variable pointing to the icons */
private seatIconTarget!: any | undefined;
private eyeIconTarget!: any | undefined;
private stageIconTarget!: any | undefined;
ngOnInit(): void {
this.setTarget.emit();
}
/** Set the icons target for dynamically modifying the style of the specific object*/
setSeatIcon(ev: any) {
console.log('setSeat');
this.seatIconTarget = ev.target;
}
setEyeIcon(ev: any) {
console.log('setEye');
this.eyeIconTarget = ev.target;
}
setStageIcon(ev: any) {
console.log('setStage');
this.stageIconTarget = ev.target;
}
And in the HTML file:
<div *ngIf="show === false" class="head">
<!-- Buttons -->
<button mat-icon-button class="icon" (click)="onIconClick('seat', $event)" (setTarget)="setSeatIcon()"
<mat-icon title="Add seats">event_seat</mat-icon>
</button>
<button mat-icon-button class="icon" (click)="onIconClick('eye', $event)" (setTarget)="setEyeIcon($event)">
<mat-icon title="Hide clicked cells">remove_red_eye</mat-icon>
</button>
<button mat-icon-button class="icon" (click)="onIconClick('stage', $event)" (setTarget)="setStageIcon($event)">
<mat-icon svgIcon="stage" title="Add stage"></mat-icon>
</button>
</div>
In the chrome console, the console.log() that i wrote in the setSeatIcon, setEyeIcon and setStageIcon functions are not getting displayed, this means that the function is not being executed. If i console log the three variables that i define at the beginning of the code, they are all undefined.
The event emitter declaration looks correct to me, but I don't know why the event is not getting emitted.
Thank you very much for the possible solutions! :)
Solution
The EventEmitter purpose in Angular is used for notification when an event (like button click) is fired, Angular bind this event to a method in ts file:
public onClick(event) {
this.setTarget.emit();
}
Having the emit call in ngOnInit won't serve anything, all three setSeatIcon, setEyeIcon and setStageIcon
functions are bind to click event so without clicking they also won't trigger, that's why no console.log was printed. If you want to trigger an event like click, just simply do the things you want inside those three functions, if you want to fire out an event that happen inside a child component to outer component (parent component) then use emit()
. I hope this helps!
Answered By - Thuan Tran
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.