簡體   English   中英

角度:將ngFor中的單個對象傳遞給路由器鏈接的組件

[英]Angular: pass single object within ngFor to router linked component

單擊鏈接后,如何將<a>標記(在volume-links.component.html中)內的數據綁定信息傳遞給我的頁面視圖組件。

我想將該特定的日記對象傳遞給我的網頁瀏覽。

我已經研究了父級和子級組件的交互,但是我認為這不是正確的方法。 我已經研究過通過服務進行通信,但是我不知道如何解決此類問題。

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);
  })
 }
}

您想看一下https://angular.io/guide/component-interaction

有幾種方法/方法可以實現這一目標,並根據您的用例選擇一種。

我將在VolumeLinksComponent中定義一個Input屬性,並在其中傳遞日記對象(這是第一部分“通過輸入綁定將數據從父項傳遞給子項”)。

這看起來像:

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

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

該父組件當然需要一個屬性“ selectedDiary”和一個方法:

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

但是在您提供的情況下,由於您想從api檢索詳細信息,似乎只需要特定的ID? 在這種情況下,您只需定義一個帶有ID的路線,並在訪問該路線時要求其他DiaryService檢索您需要的內容。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM