8

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 3

12

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;
    })
  );
}
Sign up to request clarification or add additional context in comments.

Comments

4

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

1 Comment

This seems a more proper way than the accepted answer.
1

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.