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

时间:2017-03-11 11:40:54

标签: angularjs angular

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

通常我会创建一个父组件并在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)

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

目前的做法, 隆重-父 - component.html:

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

建议的方法, 隆重-父 - component.html:

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

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

1 个答案:

答案 0 :(得分:6)

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

<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>

这就是你要找的东西吗?

相关问题