I created a boolean isStationSelected
to know if the element is selected or not.
In which case I show a select button. The problem is that the value never updates.
I have tried plenty of solution, like this one or this article and many others, but none of theme worked.
I have tried some other solutions found on internet but no success, the value stay to the initial state.
html
<div>
<div #station>
{{isStationSelected}} // always false
</div>
<button
[ngClass]="{'hidden': !isStationSelected, 'block': isStationSelected}">
Select
</button>
</div>
ts
...
@ViewChild('station') station: ElementRef;
public isStationSelected: boolean = false
constructor(
private renderer: Renderer2
) {
this.renderer.listen('window', 'click', (e: Event) => {
this.station.nativeElement.contains(e.target) ?
this.isStationSelected = true :
this.isStationSelected = false
})
}
...
I reproduced exactly what I have https://stackblitz.com/edit/ionic-angular-v5-cljwhp?file=src/app/app.component.ts
But I do not get the problem in stackblitz... I think this is beceause ionic on a device. But how to fix it, or to detect outside clicks ?
I also tried to use a toggle function
toggle() {
this.isStationSelected = !this.isStationSelected
console.log("fired");
}
Which works nice when it is not in an event listener like this.renderer.listen('window', 'click')
or document.addEventListener("click")
for exemple.
(If I use the toggle()
function in a button
on click it works fine)
The logs are always good, I mean this.isStationSelected
as the value it should in the console, and the log fired
is well displayed.
But the value does not change in front.