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

Eik*_*nds 3 angularjs angular

我想知道是否可以定义父组件而不指定使用哪个子组件?

通常我会创建一个父组件并在html文件中使用子组件的选择器

母体组分-1.HTML:

//some logic
<child-component-1-selector></child-component-1-selector>
//some logic
Run Code Online (Sandbox Code Playgroud)

如果我遵循这种方法,我必须定义我想使用哪种子组件.但是,如果我想多次使用父组件与不同的子组件,我必须复制逻辑部分并创建单独的父组件:

母体组分-1.HTML:

//some logic
<child-component-1-selector></child-component-1-selector>
//some logic
Run Code Online (Sandbox Code Playgroud)

母体组分-2.HTML:

//some logic (same as above)
<child-component-2-selector></child-component-2-selector>
//some logic (same as above)
Run Code Online (Sandbox Code Playgroud)

我不喜欢这种方法,因为我会生成代码重复.有没有办法定义父组件而不指定要呈现的子组件,只是将子组件"传递"为参数?

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

<parent-component-1></parent-component-1>
<parent-component-2></parent-component-2>
Run Code Online (Sandbox Code Playgroud)

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

<parent-component-selector [childcomponent] = "child-component-1"></parent-component-selector>
<parent-component-selector [childcomponent] = "child-component-2"></parent-component-selector>
Run Code Online (Sandbox Code Playgroud)

我希望我已经清楚地了解了我的"问题".也许你们可以帮助我并就最佳实践提出建议

sno*_*ete 6

听起来你希望能够做到这样的事情:

<my-custom-panel>
   <here-is-one-inner-component>
</my-custom-panel>
Run Code Online (Sandbox Code Playgroud)

然后在另一个地方

<my-custom-panel>
   <some-other-component>
</my-custom-panel>
Run Code Online (Sandbox Code Playgroud)

如果我正确地读你,那么你基本上都在考虑使用Angular的内容投影.

因此,在上面的示例中,我将自定义面板组件编写为如下所示:

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

诀窍是<ng-content>标记,它充当组件模板中的标记.在另一个模板中使用my-custom-panel时,my-custom-panel标记内显示的任何内容都会直接投射到该<ng-content>标记旁边.

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

<my-custom-panel>
   <here-is-one-inner-component>
</my-custom-panel>
Run Code Online (Sandbox Code Playgroud)

这将转变为:

<div class="wrapper">
       <h1>My Heading</h1>
       <ng-content></ng-content>
       <here-is-one-inner-component>
</div>
Run Code Online (Sandbox Code Playgroud)

这就是你要找的东西吗?

  • 这正是我正在寻找的。有时在不知道所需关键字的情况下很难搜索。在我的情况下,关键字似乎是“transclusion”(https://scotch.io/tutorials/angular-2-transclusion-using-ng-content)。谢谢! (2认同)