Is binding to an Observable<enum>
possible like this in Angular?
<a [ngClass]="{selected: (mapToolBarMode$ | async) === 0 }" />
or
<a [ngClass]="{selected: (mapToolBarMode$ | async) === MapMode.Pan }" />
where mapToolBarMode$
is the observable
It doesnt seem to do anything as the observable mutates.
I think it could be to do with the value not being available in the constructor, if I do this it works, but I dont really want to do that for every value in the MapMode enum:
private mapModes: typeof MapMode = MapMode;
private isPanSelected = true;
ngOnInit() {
this.mapToolBarMode.subscribe(v => {
this.isPanSelected = (v === this.mapModes.Pan);
})
}
...
[ngClass]="{selected: isPanSelected }"
Update turns out this was to do with legacy code calling angular components. those calls need to run under the context of an ngZone, otherwise there's no cycling
Combining NgStyle and NgClass Directives with our knowledge of Angular Template Syntax, we can marry conditional styling with Angular's Property & Event Binding.
ng-style is used to interpolate javascript object into style attribute, not css class. And ng-class directive translates your object into class attribute.
The ngClass directive allows you to dynamically set CSS classes on an HTML element by databinding an expression that represents all classes to be added.
Maybe you missed a detail in your question, in my example its working fine:
Or your observable is already completed
? Http request maybe?
@Component({
selector: 'my-app',
template: `
<div>
<h2 (click)="toggle()"
[ngClass]="{selected: (mapToolBarMode$ | async) === 0 }"
>
Hello {{name}}, click to toggle color
</h2>
</div>
`,
styles: [
'.selected { color: red; }'
]
})
export class App {
name:string;
mapToolBarMode$ = new Subject();
constructor() {
this.name = 'Angular2'
}
private _curState = 1;
toggle() {
if (++this._curState > 1) this._curState = 0;
this.mapToolBarMode$.next(this._curState);
}
}
live demo: https://plnkr.co/edit/h0YIPpCh9baJgxCsBQrY?p=preview
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With