Search code examples
htmlangularangularjsangular-directiveangular-components

Confusion regarding scope of button inside angular


(click) event in one instance of a component is triggering function in another instance. I don't know how to explain this. I've attached a stackblitz example.

Clicking on both the buttons print same id even though different ids have been passed to their instances. Ideally clicking on first button should print 1 and second button should print 2


Solution

  • The problem is that you're really click to the first button ALWAYS

    You button have a label over it. So, really you click to the label, not the button. Your's labels have for="my_btn" and the "id" of both buttons are my_btn

    If you remove the class "btn" of your button and you click the "labels" you can see what on earth I'm saying.

    You can in your component.ts (outside the component) declare a variable uniqueId, and a variable of the component unique id in the way

    let nextUniqueId = 0; //<--see that it's outside the component. 
                          //It's a variable of the "document"
    @Component({
      selector: 'app-mybutton',
      standalone: true,
      templateUrl: './mybutton.component.html',
      styleUrl: './mybutton.component.css',
    })
    export class MybuttonComponent {
      @Input() id:number
      uniqueId='btn'+nextUniqueId++  //<--give a property uniqueId of the component
                                     //and incremente la variable document.nextUniqueId
      constructor(){
      }
    
      func() {
        console.log(this.id);
      }
    }
    

    In your .html "binding to uniqueId of the .ts

    <button class="btn" [id]="uniqueId" (click)="func()">mybutton</button>
    <label [for]="uniqueId" class="label">label_btn</label>
    

    A stackblitz

    NOTE: If this "work-around" looks like strange, it's the same material angular use, e.g. in the radio-buttons (you can see in the github)