Angular query params as boolean type, not string

Viewed 5839

I'd like to pass a query parameter to an *ngIf but this keep evaluating to true due to being a string type. How do I change my query parameter to a boolean so it will evaluate as false?

The query param is ?paywall=true but is still true with the query ?paywall=false

component.ts

ngOnInit() {
    this.paywallQuery$ = this.route.queryParamMap.pipe(map(params => params.get('paywall')));
}

component.html

<div *ngIf="(paywallQuery$ | async)"> <-- always evaluates as true
</div>
3 Answers

Map the value to a boolean by performing a string comparison against 'true'.

ngOnInit() {
  this.paywallQuery$ = this.route.queryParamMap.pipe(
    map(params => {
      const value = params.get('paywall');
      return value ? value.toLocaleLowerCase() === 'true' : false;
    })
  );
}

If I already depend on Angular's CDK I would use the boolean coercion function (coerceBooleanProperty) to convert that string to a proper boolean.

It's pretty bare bones, but this is the thing with urls and attributes in the web component space vs using javascript to do the binding. queryparams, pathparams, and attributes are all string values so you gotta convert them for them to make sense in your implementation.

This would be my code:

import { coerceBooleanProperty } from '@angular/cdk/coercion';
this.paywallQuery = coerceBooleanProperty(this.route.snapshot.paramMap.get('paywall'))

and you can see some examples here: https://github.com/angular/components/blob/master/src/cdk/coercion/boolean-property.spec.ts

You can parse the parameters using JSON.parse. The boolean string value will become a real boolean.

Full code:

export class Page implements OnInit {
  public paywallQuery: boolean;

  constructor(private activatedRoute: ActivatedRoute) {}

  public ngOnInit() {
    this.paywallQuery = this.getPayWallValueFromQueryParams();
  }

  private getQueryParams() {
    return this.activatedRoute.snapshot.params;
  }

  private getPayWallValueFromQueryParams(): boolean {
    return JSON.parse(this.getQueryParams().paywall);
  }
}

Note: I used the snapshot instead of the observable query params, therefore:

<div *ngIf="paywallQuery"></div>
Related