[英]How do i display a Angular component inside another Angular component
假設我有兩個組件, Component1
和Component2
。 其中Component2
需要一些參數來渲染。
是否可以僅在Component2
內顯示Component1
的內容。 只需單擊按鈕即可觸發這些參數?
例如,假設我有GalleryComponent
和ArtsComponent
。
{ 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.