I want to use routerLink in angular app.
app.module.ts
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule,
RouterModule.forRoot([
{
path: 'details/:title',
component: NewsDetailsComponent
},
{
path: '',
component: AppComponent
}
])
],
exports: [RouterModule]
app.component.html
<ul>
<li *ngFor="let article of articles" >
<img src="{{article.urlToImage}}">
<a [routerLink]="['/details',article.title]">
<h1 (click)="goToOtherComponent()" >{{article.title}}</h1>
</a>
<p>{{article.description}}</p>
<p>By <span>{{article.author}}</span></p>
</li>
</ul>
app.component.ts
import { Component, OnInit } from '@angular/core';
import { Http } from '@angular/http';
import { NewsService } from './news.service';
import { Router } from '@angular/router';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
ngOnInit() {
this.getArticles();
}
constructor(public service: NewsService, private router: Router) {}
title = 'google-news';
articles;
// get data from service
getArticles() {
this.service.getNews().subscribe(data => {
console.log(data);
this.articles = data['articles'];
});
}
goToOtherComponent() {
this.router.navigate(['/details']);
}
}
i tried programmatic navigation from app component to news-details component holding some data but i don't know what's wrong with my code..any help ?
@R.cs
You add router-outlet
in your app.component.html
based on router your component will render.
keep router-outlet in your app.component.html other that that just remove in your component.
Ref: https://stackblitz.com/edit/angular-6wfpnx?file=src%2Fapp%2Fapp.component.ts