【问题标题】:Angular 2 - base class incorporates child class templateAngular 2 - 基类包含子类模板
【发布时间】:2017-08-21 12:46:32
【问题描述】:

我尝试为基类定义一个弹出窗口(带有边框、标题和关闭按钮),并且窗口内部应在子类和模板中定义

我阅读了很多继承教程,但每次子类都会覆盖基类模板而不是在其中注入

我应该使用继承吗?聚合?指令?在这种情况下,我可以将组件类作为指令的参数传递吗?

基类:

import { Component, OnInit } from '@angular/core';

@Component({
    selector: 'my-popup-window',
    templateUrl: './popupWindow.component.html',
    styleUrls: ['./popupWindow.component.css'],
})

export class PopupWindow implements OnInit {

    constructor(
    ) { }

    ngOnInit() {

    }

}

基本模板:

<div class="popupWindowMainDiv">
    <!-- here should be injected child class stuffs -->
</div>

子类:

import { PopupWindow } from '../popupWindow/popupWindow.component';

export class ProductSelectorComponent extends PopupWindow implements OnInit {

谢谢

【问题讨论】:

    标签: angular templates inheritance


    【解决方案1】:

    当你在 typescript/angular 中扩展类时,只有内部结构和元被继承。无法继承类注释 (@Component)。所以当你扩展指令时,你必须完全覆盖@Component注解的所有参数。

    @Component({
        selector: 'my-another-popup-window',
        templateUrl: './popupWindow.component.html',
        styleUrls: ['./popupWindow.component.css'],
    })
    export class ProductSelectorComponent extends PopupWindow implements OnInit {}
    

    在你的特殊情况下,你应该有类似的东西:

    //popupWindow.component.html
    <div class="header"><ng-content select="[header]"></ng-contents></div>
    <div class="body"><ng-content select="[body]"></ng-contents></div>
    <div class="footer"><ng-content select="[footer]"></ng-contents></div>
    
    @Component({
        selector: 'my-another-popup-window',
        templateUrl: `
            <my-popup-window>
                <div header><h1>My Header</h1></div>
                <div body><!-- some content --></div>
            </my-popup-window>
        `,
        styleUrls: ['./popupWindow.component.css'],
    })
    export class ProductSelectorComponent{}
    

    【讨论】:

    • 它有效!感谢您花时间制作 plunkr ;-)
    猜你喜欢
    • 2017-03-12
    • 2019-05-28
    • 1970-01-01
    • 1970-01-01
    • 2013-01-11
    • 1970-01-01
    • 1970-01-01
    • 2017-10-26
    • 1970-01-01
    相关资源
    最近更新 更多