Pass function by two way data bind

Asked

Viewed 109 times

0

I was wondering if it’s possible to pass a function through two way data bind angular. I will try to explain, I have a component with 3 buttons and I would like to use them in several parts of my project. Wanted can pass the functions to the buttons 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 buttons in my html.

If I perform the functions and ask for one 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 on the functions to my component-btns.

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

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 mounted, in the template you want to use the Component-btns you can use Event Binding us Output you defined. Example:

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

That way, when the button is clicked, it will perform the function from within the Componentbtns that will issue an event, in which its parent component will be listening and responding.

  • It worked perfectly, I was trying to do it in a completely different way, you saved my rsrs day, thank you very much

  • Available, the documentation of Angular helps a lot, when you can give a read, it has quite interesting thing.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.