Pass function by two way data bind



  • I wonder if it is possible to pass a function through two way data bind of the angle. I'll try to explain, I have a 3-button component and I'd like to use various parts of my project. I want you to pass the functions for the buttons to run, I will try to give an example.

    component where I want to implement my buttons:

    <div>
      <component-btns [(botao1)]="funcao1" [(botao2)]="funcao2" [(botao3)]="funcao3"><component-btns>
    </div>
    

    These functions will be received in my component-btns and referenced to the buttons in my html.

    If I perform the functions and ask for a console.log(this) what will be printed is the this of mine component-btns and not this I used to implement and pass the functions to my component-btns.

    Is it really confusing what I want to do, I wonder if it's possible to do something like that?



  • You can do something like this: inside your component-btns you will set some Outputs

    @Component({
       selector: 'component-btns',
       templateUrl: 'component-btns.component.html'
    })
    export class ComponentBtns {
        @Output('botao1')
        botao1Event: EventEmitter<any> = new EventEmitter();
    
    @Output('botao2)
    botao2Event: EventEmitter&lt;any&gt; = new EventEmitter();
    
    @Output('botao3')
    botao3Event: EventEmitter&lt;any&gt; = new EventEmitter();
    
    botao1Click() {
        this.botao1Event.emit();
    }
    
    botao2Click() {
        this.botao2Event.emit();
    }
    
    botao3Click() {
        this.botao3Event.emit();
    }
    

    }

    You can read about the EventEmitter https://angular.io/api/core/EventEmitter

    Having this mounted, in the template you want to use component-btns you can use event in Output that you defined. Example:

    <component-btns (botao1)="funcaoBotao1()" (botao2)="funcaoBotao2()" (botao3)="funcaoBotao3()"><component-btns>

    In this way, when the button is clicked, it will perform the function within the ComponentBtns that will issue an event, in which your parent component will be listening and responding.




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2