I have the following component:
nav.component.ts
import { Component, OnInit } from '@angular/core';
import { ApiService } from '../api.service';
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-nav',
templateUrl: './nav.component.html',
styleUrls: ['./nav.component.css'],
providers: [ApiService]
})
export class NavComponent implements OnInit {
menus;
id;
constructor(private api: ApiService, private route: ActivatedRoute) { }
ngOnInit() {
this.route.queryParams.subscribe(queryParams => { this.id = queryParams.id });
this.api.getMenus().subscribe(res => {this.menus = res});
this.route.params.subscribe(routeParams => {
this.set_id(routeParams.id)
})
}
set_id(id){
this.id = id
console.log(this.id)
}
}
In this component a menu is being loaded and a variable is being set from a route.param coming from the following link:
nav.component.html
<div *ngFor="let menu of menus; index as id">
<ul>
<li><a routerLink ="content/{{id}}" (click)="set_id(id)">{{menu['course-lesson-name']}}</a></li>
</ul>
</div>
The app loads just fine, but the content only updates a single time. After any single menu item is clicked, the content is shown, but then I lose functionality in that any subsequent click loads nothing. If I manually manipulate the url in the browser for each link, the content loads as needed so Im assuming something is wrong with the linking. BTW, the id is being set as required and is logging to the console, but doesnt reload the content as needed based on its value.
Here is the router if needed:
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { ContentComponent } from './content/content.component';
import { HomeComponent } from './home/home.component';
const routes: Routes = [
{path: 'content/:id', component: ContentComponent},
{path: '', component: HomeComponent}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
The id should be stored and passed to the content.component.ts so getContent() can use it to parse the correct content element from the response:
content.component.ts
import { Component, OnInit, OnChanges, Input } from '@angular/core';
import { ApiService } from '../api.service';
import { RouterLink, ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-content',
templateUrl: './content.component.html',
styleUrls: ['./content.component.css'],
providers: [ApiService]
})
export class ContentComponent implements OnInit {
content;
id;
constructor(private api: ApiService, private route: ActivatedRoute) { }
ngOnInit(){
this.route.queryParams.subscribe(queryParams => { this.id = queryParams.id });
this.api.getContent().subscribe((res : any[]) => {this.content = res[this.id]})
this.api.getContent().subscribe((res) => {this.content = res[this.id]})
}
}