Search code examples
angularangular2-routingrouterangular2-services

How to create dynamic routerlinks in angular 2?


I am new at angular 2 and I am trying to create a news website which means the home page for example contains different articles from different categories .

So I get the articles for example in the slider section from api the json result contains the link ex: '/slider/article1' , '/sport/article3' etc ..

when I try to loop the results in the html the routerlink doesn't work !

Here is a sample code

Home.component.html // lets say that link contains '/sport'

<a [routerLink]="[item.link]">{{item.title}}</a>

Route.config.ts

export const rootRouterConfig: Routes = [
  { path: '', redirectTo: 'home', pathMatch: 'full' },
  { path: 'home', component: HomeComponent },
  { path: 'sport', component: SportComponent }
];

** I forget to mention the error

Uncaught (in promise): TypeError: Cannot read property 'outlets' of null

Home.component.ts

import { Component, OnInit } from '@angular/core';
import { HomeService } from '../../_services/home.service';
import { ContentInfo } from '../../_models/content';
@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css'],
  providers: [HomeService]
})
export class HomeComponent implements OnInit {
  mainNewsItem: ContentInfo[];
  constructor(private _homeService: HomeService) {
    this.mainNewsItem = [];
  }
  ngOnInit() {
        // Get Main News Item
        this._homeService.getMainNewsItem()
            .subscribe(content => this.mainNewsItem = content,
            error => this._homeService = <any>error)
            ;
  }
}

I used *ngif

*ngIf="mainNewsItem?.length > 0"

the div is gone but why ? I mean the mainNewsItem contains data !

Thanks :)


Solution

  • You can use route parameters:

    { path: 'sport/:articleTitle', component: SportComponent },

    Source: Angular doc's: route with parameter

    In your SportComponent you can inject the ActivatedRoute in your constructor to recieve the parameters: constructor(private route: ActivatedRoute)