emanuel07
emanuel07

Reputation: 758

Angular2 check if button is pressed

How can I check if a button is pressed or not?

<anotherComponent [isPressedOkButton]="xxx">    
<button #okButton>   

p.s In JSF exists such opportunity - "not empty param[button.clientId]"

Upvotes: 0

Views: 3975

Answers (1)

slaesh
slaesh

Reputation: 16917

You have to create a variable inside of your Component if you want to do it with an input of another component. And set this variable if the button was pressed.

<another-component [isPressedOkButton]="btn.attachedProp"></another-component>
<button #btn (click)="yourClickFunction(); btn.attachedProp = true;"></button>

See a working demo: https://plnkr.co/edit/AUN40WbtoQDK4PkS4a61?p=preview

import {Component, NgModule, Input} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'

@Component({
  selector: 'my-other',
  template: `
    <div>
      <h4>other component...</h4>
      button of main component was {{buttonIsPressed ? '' : 'NOT'}} pressed.
    </div>
  `,
})
export class OtherCmp {

  @Input() buttonIsPressed = false;

  name:string;
  constructor() {
    this.name = 'Angular2'
  }
}

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>Hello {{name}}</h2>
      <button #btn (click)="btn.anyAttachedProperty = true;">click me ! :)</button>
      <br />
      <my-other [buttonIsPressed]="btn.anyAttachedProperty"></my-other>
    </div>
  `,
})
export class App {

  name:string;
  constructor() {
    this.name = 'Angular2'
  }
}

@NgModule({
  imports: [ BrowserModule ],
  declarations: [ App, OtherCmp ],
  bootstrap: [ App ]
})
export class AppModule {}

Upvotes: 1

Related Questions