Pass function through two way data bind

0

I wanted to know if it is possible to pass a function through the two way data bind of the angle. I'll try to explain, I have a 3-button component and would like to use them in several parts of my project. I wanted to pass the functions to the buttons to run, I'll 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 run the functions and ask for a console.log(this) what will be printed is the this of my component-btns and not the this that I used to implement and pass the functions to my component-btns .

It's pretty confusing what I want to do, I wonder if it's possible to do something like this?

    
asked by anonymous 19.01.2018 / 17:23

1 answer

2

You can do something like this: inside your component-btns you will define 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<any> = new EventEmitter();

    @Output('botao3')
    botao3Event: EventEmitter<any> = new EventEmitter();

    botao1Click() {
        this.botao1Event.emit();
    }

    botao2Click() {
        this.botao2Event.emit();
    }

    botao3Click() {
        this.botao3Event.emit();
    }
}

You can read about the EventEmitter here

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

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

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

19.01.2018 / 18:03