簡體   English   中英

將角值發送到另一個組件

[英]Send Angular Value to another component

在我的應用程序中,我有一個菜單,可通過ID路由內容,但也有一個詳細的視圖,顯示內容的位置(通過相同的ID)。

我試圖通過單擊按鈕按其ID顯示對象,但不確定如何將ID值傳遞給item-detail組件以使其按ID顯示內容。 我需要的所有數據都可以在服務中使用。

我已經通過ID進行了路由,效果很好

path: ':id',
component: ItemDetailComponent,
data:
{
    title: 'Item Detail',
}

item.component.html (菜單組件)

在這里我觸發一個事件

<ng-container *ngFor="let item of items">
    <button (click)="getId(item.id);"></button>

item.component.ts (菜單組件)

在這里我得到對象的ID

getId(datavalue: number) 
{
      console.log(datavalue); 
}

當我單擊按鈕時,我在控制台日志中獲得了正確的ID。

現在,我想按ID在詳細視圖中顯示內容,但不確定如何將ID傳遞給此組件。

item-detail.component.html也許是這樣的?

<div>
    <h2>Text Content</h2>
    <p>
        {{glossar[datavalue]?.textContent}}
    </p>
</div>

任何幫助表示贊賞!

如果我對您的理解很好,則應將ID作為該組件的@Input()參數傳遞給item-detail組件,如下所示:

 @Input()
 id: number;

HTML:

<item-detail-component [id]="item.id"></item-detail-component>

然后通過該ID在item-detail-component加載數據中獲取詳細信息。

由於使用路由模塊,因此應該使用路由。

<button [routerLink]="[item.id]" (click)="getId(item.id);"></button>

如果您已經正確設置了帶有路由器出口的路由,並選擇了正確的路由,則應該可以使用。

在您的組件中,使用激活的路線獲取您的ID

constructor(private route: ActivatedRoute) { this.id = route.snapshot.params.id; }

暫無
暫無

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

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