-1

In this stackblitz example

When I click on red button, I should only see red in console and not gray. How can I achieve that?

    import { Component, Input } from '@angular/core';

@Component({
  selector: 'hello',
  template: `
<button style="height: 100px; width: 200px;" (click)='gray()'> Gray
<button style="height: 20px; width: 40px; background-color:red" (click)='red()'>
Red
</button>
</button>`,
  styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent {
  red() {
    console.log('red');
  }

  gray() {
    console.log('gray');
  }
}

Edit: I have tweaked the question to be a button inside a div

dota2pro
  • 7,220
  • 7
  • 44
  • 79
  • Possible duplicate of [Can I nest button inside another button?](https://stackoverflow.com/questions/39386497/can-i-nest-button-inside-another-button) – SGalea Aug 12 '19 at 14:53
  • It is not valid to put a – SGalea Aug 12 '19 at 14:58
  • I can imagine a screen reader figuring out the button roles. Just because it works doesn't mean you should. – SGalea Aug 12 '19 at 15:07

1 Answers1

1

I've updated your code below. When you click the red button you want to pass the click event (seen as $event) and then using this event, in the method you are calling, add event.stopPropogation(); to stop the next mouse event from firing.

import { Component, Input } from '@angular/core';

@Component({
  selector: 'hello',
  template: `
<button style="height: 100px; width: 200px;" (click)='gray()'> Gray
<button style="height: 20px; width: 40px; background-color:red" (click)='red($event)'>
Red
</button>
</button>`,
  styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent {
  red($event: MouseEvent) {
    console.log('red');
    $event.stopPropagation();
  }

  gray() {
    console.log('gray');
  }
}

PS. Ultimately you shouldn't be nesting buttons though.

Bren Gunning
  • 153
  • 2
  • 9