簡體   English   中英

如何在另一個 Angular 組件中顯示 Angular 組件

[英]How do i display a Angular component inside another Angular component

假設我有兩個組件, Component1Component2 其中Component2需要一些參數來渲染。

是否可以僅在Component2內顯示Component1的內容。 只需單擊按鈕即可觸發這些參數?

例如,假設我有GalleryComponentArtsComponent

  { path: 'gallery', component: GalleryComponent },
  { path: 'arts', 
    children: [
      { path: '', component: ArtsComponent, data :{ name:"all" } },
      { path: 'author/:id', component: ArtsComponent, data :{ name:"author" }},
      { path: 'form/:id', component: ArtsComponent, data :{ name:"form" } },
    ]
  }

目前,我可以將這兩個都視為以下URLS

localost:4200/gallery
localost:4200/arts
localost:4200/arts/author/1
localost:4200/art/form/1

我正在導航,

[routerLink]="['/arts/form', '1']"

這將帶我進入新頁面,即localost:4200/art/form/1 ,但我不希望這樣,我只想在我的GalleryComponent中捕獲此URL的內容,例如,

//gallery.component.html
<a [routerLink]="['/arts/form', '1']">Form1</a>
<a [routerLink]="['/arts/form', '2']">Form1</a>

<app-arts></app-arts>

您可以在另一個下嵌套幾乎任意數量的組件,只要該組件具有<router-outlet></router-outlet>它將 output 子路由的內容。 app.component的工作方式相同。 因此,您需要做的就是將router-outlet放在galery.component.html中,然后在路由配置中將ArtsComponent放在GaleryComponent的 children 數組中。 之后,您還將調整ArtsComponent的路線

[
  { 
    path: 'gallery', 
    component: GalleryComponent, 
  }, 
  { 
    path: 'arts', 
    component: GalleryComponent, 
    children: [ 
        { path: '', component: ArtsComponent, data :{ name:"all" } }, 
        { path: 'author/:id', component: ArtsComponent, data :{ name:"author"}}, 
        { path: 'form/:id', component: ArtsComponent, data :{ name:"form" }}, 
    ]
  },
]
----------------------------------
//gallery.component.html

<a [routerLink]="['/gallery/form', '1']">Form1</a>
<a [routerLink]="['/gallery']">All</a>
<a [routerLink]="['/gallery/author','1']">Author</a>

<router-outlet></router-outlet>

為了實現這一點,您需要向您的gallery.component.html添加另一個<router-outlet> ,然后將藝術路線添加為module中畫廊組件的子項

嘗試這個。

export class Component1 {


}

在 HTML 中添加您的第二個組件:

<app-component2></app-component2>

暫無
暫無

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

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