[Fixed] where to declare a variable referenced from inside ngOnInit()

Issue

the below posted code is from https://angular.io/guide/router
the code works fine but it does not exhibit where exactly name variable should be defined

please let me know how to fix it

code:

import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute, ParamMap } from '@angular/router';

@Component({
  selector: 'app-first',
  templateUrl: './first.component.html',
  styleUrls: ['./first.component.css']
})
export class FirstComponent implements OnInit {

  constructor(private route: ActivatedRoute) { }

  ngOnInit(): void {
    this.route.queryParams.subscribe(params => {
      this.name = params['name'];
    });
  }

}

Solution

name should be a property of FirstComponent class.

export class FirstComponent implements OnInit {

    name : string;

    constructor(private route: ActivatedRoute) { }

    ngOnInit(): void {
        this.route.queryParams.subscribe(params => {
            this.name = params['name'];
        });
    }
}

I recommend that you do Tour of Heroes if you don’t know the basics.

Leave a Reply

(*) Required, Your email will not be published