【问题标题】:Angular2: base component - panel with title and contentAngular2:基础组件 - 带有标题和内容的面板
【发布时间】:2016-06-15 07:38:04
【问题描述】:

我想创建表示基本面板的组件(使用 HTML 模板)。然后我想继承这个基类,但只指定标题(作为类属性/函数或@Input)和内容(作为@Component 装饰器中的templatetemplateUrl)。

@Component({
    template: `
        <div class="panel">
            <div class="title">{{title}}</idv>
            <div class="content">???</div>
        </idv>
    `
})
export class BasePanel {
    @Input()
    protected title: string = '';
}

@Component({
    selector: 'my-panel',
    template: `MyPanel template - lorem ipsum`
})
export class MyPanel extends BasePanel {
    title: string = 'MyPanel title';
}

然后在其他模板中:

<my-panel></my-panel>

<my-panel title="My better panel"></my-panel>

非常好的解决方案是在 HTML 标记之间传递内容:

<my-panel title="My panel with content">
    <p>Lorem ipsum dolor sit amet,</p>
    <p>consectetur adipiscing elit.</p>
</my-panel>

编辑 1

@rinukkusu 提供的带有 ng-content 的解决方案正在发挥作用。

但我希望有可能创建 BasePanel 组件来装饰派生组件模板。

【问题讨论】:

  • 我不知道“哪个会装饰派生组件模板”。方法。你能详细说明一下吗?
  • @GünterZöchbauer 在一个组件中,我只想将 HTML 用于面板内容(带有变量等),这将通过 HTML 声明填充、边距、边框等进行装饰 - 对所有面板进行相同的装饰应用。这种装饰最好由BasePanel 完成——但这种想法来自PHP。
  • 听起来像&lt;ng-content&gt; 下面解释是正确的使用方法。

标签: angular


【解决方案1】:

继承不适用于此,但您可以利用 ng-content 标记,以便它显示原始 HTML。

组件:

@Component({
    selector: 'my-panel',
    template: `
        <div class="panel">
            <div class="title">{{title}}</div>
            <div class="content"><ng-content></ng-content></div>
        </div>
    `
})
export class MyPanel {
    @Input()
    protected title: string = '';
}

用法:

<my-panel title="My panel with content">
    <p>Lorem ipsum dolor sit amet,</p>
    <p>consectetur adipiscing elit.</p>
</my-panel>

以工作Plunker为例使用

【讨论】:

  • 这是在 HTML 标记之间传递内容的好解决方案:但我希望有可能创建 BasePanel 组件来装饰派生组件模板。
  • 这行不通,就像我说的和 Günter 在他的回答中所说的那样。
【解决方案2】:

Angular 不支持扩展组件。在 Angular 中,组合优于继承。有答案建议自定义装饰器支持它,但与即将推出的离线模板编译器不兼容。

【讨论】:

  • 优先组合而不是继承是总体趋势,因为它更具弹性。但是应用视觉装饰器的最佳方法是什么?如何组织代码以仅创建面板内容(项目中有很多)而不是周围的 HTML 标签,记住即将推出的离线模板编译器和 DRY ?我可以为标题和内容装饰器开始和内容装饰器结束的标题创建子组件,并在每个面板中使用这些组件。很多年前我在 PHP 中就是这样做的,后来技术发展了。
猜你喜欢
  • 1970-01-01
  • 2017-04-16
  • 1970-01-01
  • 1970-01-01
  • 2020-04-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多