简体   繁体   中英

Angular: pass single object within ngFor to router linked component

How do I pass the data binded information within the <a> tag (Within the volume-links.component.html ) to my page-view component when the link is clicked.

I want to pass that particular diary object to my page-view.

I've looked into parent and child component interaction but I don't think that is the proper way to do it. I've looked into communicating via a service but I do not know how that would work for a problem such as this.

volume-links.component.html

<ul class="navigation">
 <li *ngFor="let d of diary">
   <a id={{d.notebook_id}} routerLink="/page-view" routerLinkActive="active">Volume {{d.notebook_id}}, {{ d.date }}, {{ d.volume_id }}, Add MS {{ d.ms_id }}</a>
 </li>
</ul>

volume-links.component.ts

import { Component, OnInit } from '@angular/core';
import { Http } from '@angular/http';
import { HttpClient, HttpClientModule } from '@angular/common/http';
import 'rxjs/add/operator/map'

@Component({
  selector: 'app-volume-links',
  templateUrl: './volume-links.component.html',
  styleUrls: ['./volume-links.component.scss'],
  //encapsulation: ViewEncapsulation.None
})
export class VolumeLinksComponent implements OnInit {

diary : String;

constructor(private http: HttpClient) { }

ngOnInit() {
  this.http.get('/api/diaries').subscribe(data => {
    this.diary = data["data"]["docs"];
    console.log(this.diary);
  })
 }
}

You want to look at https://angular.io/guide/component-interaction

There are several methods / ways to achieve this and depending on your use case choose one.

I would define an Input property in VolumeLinksComponent and pass the diary object in there (that's the first part "Pass data from parent to child with input binding").

This would look something like:

<a *ngFor='let diary of diaries' (click)='chooseDiary(diary)'>

<my-diary-container [diary]='selectedDiary'></my-diary-container>

and that parent component of course needs a property 'selectedDiary' and a method:

chooseDiary(diary: Diary): void {
     this.selectedDiary = diary;
}

But in your provided case it seems like you just need the specific id since you want to retrieve details from the api? In that case you could just define a route with the id and when the route is accessed ask an additional DiaryService to retrieve what you need.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM