In Angular 2 you work a lot with this
, which is fine but I've found that it also creates an issue when you want to pass down a function down the component hierarchy.
Take this for example:
export class ParentComponent {
myFunctionFromParent() {
this.isActive = true;
}
}
Then we pass this function down to a child:
<parent>
<child [onClick]="myFunctionFromParent"></child>
</parent>
And let's say child
is a simple button:
<button (click)="onClick()"></button>
Now, when myFunctionFromParent
runs, this
should be the ParentComponent
but it's not.
Instead it's the ChildComponent
that will have it's this.isActive
property changed.
This creates a lot of issues as you can't execute parent functions from a child component and expect the parent properties to change.
Passing down functions works as you would expect them to do in Angular 1, but now it seems broken.
Is this no longer the way to do things like this? What is the correct way to to this in Angular 2?