Question:
- I have a component
A
and a componentB
- In my component
A
I make an instance of my componentB
Html of component A
<b [onPress]="onPressAComponent"></b>
In the .ts
of my component A
, exactly in the onPressAComponent
method, it brings me the context of component B
instead of component A
When I do console.log(this)
, it clearly shows the context of component B
I in react, I would solve it like this:
<b [onPress]="e => onPressAComponent(e)"></b>
But it gives me an error..
How do I get the context of the component itself when I use a method as a callback?
EDIT:
.ts
component B
export class DropdownSelectComponent implements OnInit {
@Input() title
@Input() name
@Input() onPress
@Input() data
constructor() { }
ngOnInit() {
}
onClick(index){
this.onPress(index)
this.name = this.data[index].name
}
}
.ts
component A (where I have the problem)
export class HomeComponent implements OnInit {
...
onPressEnvironment( index ){
console.log( this )
// devuelve: DropdownSelectComponent {title: "Entorno", name: "Selecciona", onPress: ƒ, data: Array(2)}
// deberia devolver: HomeComponent {...}
}
...
}
Answer:
What happens is that when working with angular you need to use an EventEmiiter
from component B
so that A
can instantiate it. This is done asynchronously so you have to wait for the EventEmitter
to fire. You need an @Output() miVariable = new EventEmitter<B>()
and cast it in the ngOnInit(){}
. What you're getting isn't the component instance, it's the event it's firing e
This may be a way to solve the problem:
Another way to solve it is with a service. In this way you do not get unique components and you can have problems trying to use the same component several times that depends on an injected service (because this is the same for all and for this reason it shares the data)