Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bind ngclass to an observable value

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

like image 591
jenson-button-event Avatar asked Feb 21 '17 17:02

jenson-button-event


People also ask

Can we use NgStyle and NgClass together?

Combining NgStyle and NgClass Directives with our knowledge of Angular Template Syntax, we can marry conditional styling with Angular's Property & Event Binding.

What is difference between NgStyle and NgClass?

ng-style is used to interpolate javascript object into style attribute, not css class. And ng-class directive translates your object into class attribute.

How NgClass works in angular?

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.


Video Answer


1 Answers

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

like image 162
slaesh Avatar answered Oct 04 '22 05:10

slaesh