Troubleshooting tips for accessing queryParams in ngOnInit when using Angular routing method with queryParams

Currently in the process of learning Angular Routing, I encountered an error. In the course component, I attempted to make changes to the web content by utilizing queryParams and a variable editMode: boolean with its default value set to false.

Link to Stackblitz code

Access link here

course.component.ts

export class CourseComponent implements OnInit, OnDestroy {

  constructor(private service: CoursesService, private route: ActivatedRoute, private router: Router) { }

  course: any;
  courseId: any;
  routeParamObservable: any;
  queryParamObservable: any;
  editMode: boolean = false;

  addQueryParam() {
    this.router.navigate(['/Course', this.courseId], { queryParams: { edit: true } });
  }

  //saveUpdateNameChange() {
    //this.router.navigate(['/Course', this.courseId]);
  //}

   saveUpdateNameChange() {
     this.router.navigate(['/Course', this.courseId], { queryParams: { edit: false } });
   }

  ngOnInit(): void {
    this.routeParamObservable = this.route.paramMap.subscribe({
      next: (param) => {
        this.courseId = param.get('id');
        this.course = this.service.courses.find(x => x.id == this.courseId);
      }
    })

    this.router.navigate(['/Course', this.courseId]);

    this.queryParamObservable = this.route.queryParamMap.subscribe({
      next: (param) => {
        this.editMode = Boolean(param.get('edit'));
        console.log(this.editMode);
      }
    })
  }

  ngOnDestroy(): void {
    this.routeParamObservable.unsubscribe();
    this.queryParamObservable.unsubscribe();
  }

}

course.component.html

<div class="course-container">
    <div>
        <img src="{{course.image}}" width="560" height="280">
    </div>
    <div>
        <h1 *ngIf="!editMode" style="text-align: center;">{{course.name}}</h1>
        <div *ngIf="editMode" style="text-align: center;">
            <input type="text" [(ngModel)]="course.name">
        </div>
    </div>
    <div class="course-details">
        <div style="margin: 0px 10px;"><b>Author: </b>{{course.author}}</div>
        <div style="margin: 0px 10px;"><b>Duration: </b>{{course.duration}}</div>
        <div style="margin: 0px 10px;"><b>Type: </b>{{course.type}}</div>
    </div>
    <div style="margin: 0px 10px;">
        <h2>Price: {{course.price}}$</h2>
    </div>
    <div style="margin: 20px 10px;">
        <p>{{course.description}}</p>
    </div>

    <button (click)="addQueryParam()" *ngIf="!editMode">Edit</button>
    <button (click)="saveUpdateNameChange()" *ngIf="editMode">Save Update</button>
</div>

After calling the addQueryParam() method:

  • When attempting to save the changes using
    saveUpdateNameChange() {this.router.navigate(['/Course', this.courseId], { queryParams: { edit: false } });}
    , although routing works fine, accessing queryParams in the ngOnInit method seems to be ineffective as the console log does not display "false".
  • Conversely, when invoking
    saveUpdateNameChange() {this.router.navigate(['/Course', this.courseId]);}
    without queryParams, both routing and the retrieval of queryParams within ngOnInit work smoothly, with the console log accurately showing "false".

Hence, how is it that the method for accessing queryParams in ngOnInit functions properly when called without queryParams, but fails to do so when invoked with queryParams in this specific scenario?

PS: Apologies if my query is unclear.

Answer №1

It appears that the issue lies in the boolean conversion process, as even 'false' is being logged to the console. I verified this at

When converting into a boolean, it seems Boolean always returns true, even in the case of false.

To resolve this issue, consider using the following code snippet within queryparamMap:

    console.log(param.get('edit'));
    var d = param.get('edit') || '';
    this.editMode = JSON.parse(d);
    console.log(this.editMode);

Using JSON.parse for boolean conversion may help rectify the problem.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Essential front-end tools for enhancing Angular 2 projects

Hi there! I specialize in Laravel development and am currently diving into the world of Angular 2 framework. Up until now, I've been handling my third-party front end assets through bower, using a bower.json file to manage dependencies. Check out a sn ...

Angular: Ensure that form control is disabled correctly to preserve the value for later retrieval

Here is my angular reactive form setup: zoneEntryForm = new FormGroup({ code: new FormControl(''), zonename: new FormControl(''), }); The output I'm getting from this code is: onSubmit() { // TODO: Use EventEmitt ...

Changing function arguments in TypeScript using the spread operator

Could the Tuple spreading syntax in Typescript be utilized to consolidate these function overloads? The challenge lies in the necessity to refactor the function arguments into new types. type Type = TString | TNumber type TString = { tag: 'string&apos ...

Methods for organizing consecutive elements within an array in Javascript/Typescript

Let's explore this collection of objects: [ { key1: "AAA", key2: "BBB" }, { key1: "BBB", key2: "CCC" }, { key1: "CCC", key2: "DD ...

Ways to effectively implement a function type specified in an interface

Consider the following interface: interface MyProps { onEvent: (name: string, data: any) => void; } Is there a way to utilize the function type in order to avoid unused parameter errors during compilation? eventHandler = (name: string, data: any) = ...

The functionality of Change Detection is inconsistent when data is being received from the Electron Container IPC Channel

I have a program that is waiting for incoming information from an IPC Renderer Channel. Here is how I have it set up: container sending data to Angular app (mainWindow): mainWindow.loadURL('http://www.myangularapp.com') //location of the angul ...

The parameter '""' cannot be assigned to type '"prototype"' according to jasmine

Update: It seems that the following code snippet is working fine: let gaService = TestBed.get(GAService); and I can spy on gaService. I am currently unsure of what exactly I am missing here. The service is responsible for sending data to Google Analyti ...

Protractor experiencing difficulty recognizing Angular functionality

Recently, I made the switch to using Protractor for running end-to-end tests on my Angular application. However, the e2e tests have suddenly started failing because Protractor is unable to detect Angular on the website. I raised this issue in their GitHub ...

What methods can be used to disable Angular's change detection feature?

I am attempting to create a function that can handle both synchronous and asynchronous tasks without triggering change detection upon completion. This function is being triggered by a button click in the user interface. Template file: <button (click)=& ...

Exploring the Possibility of Retrieving and Showing a PDF File from a Server in Angular 2 RC 5

I am currently working on integrating a PDF generated by a server into a view within my Angular 2 RC 5 project. The ASPNETCORE server is transmitting the object as an 'application/pdf', while the Angular client is attempting to interpret the resp ...

Invoking Angular component method using vanilla JavaScript

For my web application, I am utilizing Angular and require Bluetooth functionality on a specific page. I am implementing loginov-rocks/bluetooth-terminal (https://github.com/loginov-rocks/bluetooth-terminal) for establishing the Bluetooth connection, which ...

`Are you incorporating Material UI tabs with React Router in your project?`

Looking for help with a project utilizing react/typescript. Here's the react router configuration: const Root = () => ( <> <NavBar/> <Router> <Route path="/" component={Home} /> <Route ...

Tips for getting the array element in the 'field' attribute of the PrimeNG autoComplete

In my possession is a collection of JSON objects, here's an example: [ { id: 'cont-609', contactMedium: [ { characteristic: { emailAddress: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__ ...

Encountering issues when attempting to compile in Angular due to a not assignable error while creating a new interface

Trying to create a new interface for my simple project but running into a compile error. Any ideas on what I did wrong? Here's the error message: C:/Users/vashon/Angular/Angular-GettingStarted-master/APM/src/app/products/product-list.component.ts (1 ...

Order an array based on a specified list of fields

Imagine you have an array of objects: People = [ { "id": 1, "name": Joseph, function: "preacher"}, { "id": 2, "name": Ann, function: "singer"}, { "id": 3, "name": Miles, functi ...

Ways to resolve Cross-Origin Resource Sharing (CORS) issue encountered in Report

I am currently working on an Angular project and trying to render SSRS reports within the app by utilizing a specific package. The application is hosted at http://localhost:52698/ while the SSRS server resides on a different domain http:\ssrsserv ...

Encountering TS 2694 Error while running the ng serve command

I'm encountering some troublesome errors while attempting to run my angular application. Honestly, I can't figure out what's wrong, so I'm hoping someone here can assist me. I didn't make any significant changes, just added a singl ...

Utilizing Typescript for manipulation of Javascript objects

Currently, I am working on a project using Node.js. Within one of my JavaScript files, I have the following object: function Person { this.name = 'Peter', this.lastname = 'Cesar', this.age = 23 } I am trying to create an instanc ...

How can I assign a true or false value to an input variable in HTML using AngularTS?

I copied the following HTML code: <tag-input fullWidth id="inputDir" formControlName="inputDir" [modelAsStrings]="true" [placeholder]="'choice feature'" ...

Tips for managing nested data in Angular 4 using a Bootstrap 4 data-table

I am currently using the Data Table from a GitHub project found at: https://github.com/afermon/angular-4-data-table-bootstrap-4-demo. It works perfectly with data structured in a key-value format like the sample provided. However, I am facing challenges wh ...