Search code examples
angulartypescripturlroutesngmodel

How do I display a router parameter in an input box in Angular?


I currently have my routes set as follows in my Angular project:

const routes: Routes = [
  { path: 'defect', component: AppComponent },
  { path: 'defect/:start', component: DefectComponent }
];

Then in the TS of my DefectComponent I have:

//route is declared in my parameters as ActivatedRoute
ngOnInit(): void {
    let temp = this.route.snapshot.paramMap.get('start');
    if(temp) {
      this.timestamp.TestStart = temp;
    }
  }

In the html of my DefectComponent I have:

<input id="TestStart" [(ngModel)]="timestamp.TestStart" placeholder="Time">
  <button class="findSteps" (click)="createCases(timestamp)">
    Find Failed Cases
  </button>

I figured this would autofill my input with the 'start' parameter when I call it with a url like:

http://localhost:4200/defect/272020-02-06_0348100661PM

because it was added to timestamp.TestStart onInit, but right now it still is just displaying "Time." Any ideas on what I'm doing wrong?

Thoughts I've already had:

  • Does ngModel come before the ngOnInit?
  • Am I somehow passing the parameter into the url wrong?

UPDATE: temp is currently being set to null instead of the input. Any thoughts on this would be appreciated.


Solution

  • ngOnInit(): void {
        this.router.events.subscribe((event: any) => {
          let r = this.route;
          while(r.firstChild) {
            r = r.firstChild;
          }
          r.params.subscribe(params => {
            this.timestamp.TestStart = params.start;
          })
        })
      }
    

    This worked!