簡體   English   中英

Angular 2:是否可以使用具有不同子組件的相同父組件?

[英]Angular 2: Is it possible to use the same parent component with different child components?

我想知道是否可以定義父組件而不指定使用哪個子組件?

通常我會創建一個父組件並在html文件中使用子組件的選擇器

母體組分-1.HTML:

//some logic
<child-component-1-selector></child-component-1-selector>
//some logic

如果我遵循這種方法,我必須定義我想使用哪種子組件。 但是,如果我想多次使用父組件與不同的子組件,我必須復制邏輯部分並創建單獨的父組件:

母體組分-1.HTML:

//some logic
<child-component-1-selector></child-component-1-selector>
//some logic

母體組分-2.HTML:

//some logic (same as above)
<child-component-2-selector></child-component-2-selector>
//some logic (same as above)

我不喜歡這種方法,因為我會生成代碼重復。 有沒有辦法定義父組件而不指定要呈現的子組件,只是將子組件“傳遞”為參數?

當前方法,grand-parent-component.html:

<parent-component-1></parent-component-1>
<parent-component-2></parent-component-2>

建議的方法,grand-parent-component.html:

<parent-component-selector [childcomponent] = "child-component-1"></parent-component-selector>
<parent-component-selector [childcomponent] = "child-component-2"></parent-component-selector>

我希望我已經清楚地了解了我的“問題”。 也許你們可以幫助我並就最佳實踐提出建議

聽起來你希望能夠做到這樣的事情:

<my-custom-panel>
   <here-is-one-inner-component>
</my-custom-panel>

然后在另一個地方

<my-custom-panel>
   <some-other-component>
</my-custom-panel>

如果我正確地讀你,那么你基本上都在考慮使用Angular的內容投影。

所以,在我上面的例子中,我將自定義面板組件寫成如下所示:

@Component({
  selector: 'my-custom-panel',
  template: `
     <div class="wrapper">
       <h1>My Heading</h1>
       <ng-content></ng-content>
     </div>
  `
})
export class ....

訣竅是<ng-content>標記,它充當組件模板中的標記。 在另一個模板中使用my-custom-panel時, my-custom-panel標簽內顯示的任何內容都會直接投射到該<ng-content>標簽旁邊。

希望,一個例子可以讓事情變得更加清晰。 因此,在我的第一個示例中,使用my-custom-panel的模板是:

<my-custom-panel>
   <here-is-one-inner-component>
</my-custom-panel>

這將轉變為:

<div class="wrapper">
       <h1>My Heading</h1>
       <ng-content></ng-content>
       <here-is-one-inner-component>
</div>

這就是你要找的東西嗎?

暫無
暫無

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

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