Home > front end >  Button not firing Click event Angular 14.1
Button not firing Click event Angular 14.1

Time:07-22

I have an Angular Material 14.1 mat-dialog popup which allows the user to edit a list of phone numbers. As the list of phone numbers could be 0-many, I have a FormArray where each phone number has its own FormGroup of properties (number, type, name, etc). This FormArray is then assigned to a component which handles editing for that phone number:

    <ng-container formArrayName="phoneNumbers">
        <app-phone-edit *ngFor="let item of phoneNumbers.controls; index as i" (deletePhoneNumber)="deletePhone(i)"
            [formGroup]="phoneNumberFormGroup(i)"></app-phone-edit>
    </ng-container>

This component has a menu icon, and one of the options is "Delete Phone Number" which emits the event that the code above responds to.

<!-- Phone Edit Component -->
    <mat-form-field>
        <input matInput mask="0000 000 000" formControlName="phoneNumber" placeholder="Phone Number">
    </mat-form-field>
    <button mat-menu-item>
        <mat-icon aria-label="Delete Phone Number" (click)="delete()">delete</mat-icon>
        Delete Number
    </button>

In the Typescript file behind this component currently just logs the delete event to console, for testing, then emits the event:

delete(): void {
    console.log('Delete in Phone Component', this.formGroup);
    this.deletePhoneNumber.emit();
}

The problem is, the button only works sometimes. I can click "Delete" 10 times, and it will only call the code behind function once, maybe the 3rd try, maybe the 1st, maybe not at all. I have run the code in debug and there are no errors. I set a breakpoint on the delete() method, and it is only rarely called.

I can't seem to replicate this in Stack Blitz, so it seems to be something specific to my code, but the code is very straight forward. I added a new menu button "test" and the same thing happens. I feel it is something to do with the FormArray and possibly the way Angular is handling the multiple menus for each "row", or possibly there is an error occurring somewhere where I can't see it. No errors logged in console in Chrome or in debug in VSCode.

How can I troubleshoots this?

CodePudding user response:

It looks like you've attached the delete() function to the <mat-icon> element, it should be on the <button> itself.

  • Related