2017-06-02 74 views
0

我想创建一个父类(Event),它将处理四个孩子(投票事件,视图事件,我的事件,我的票)的DOM。从父项继承选择器

这个想法将是一个唯一的HTML,一个父级Compoment和4个子组件,它将覆盖一些父级方法。这是典型的多态情况。

总之,我有一个父组件:

@Component({ 
    selector: 'app-events', 
    templateUrl: './events.component.html', 
    styleUrls: ['./events.component.css'] 
}) 

export abstract class EventsComponent implements OnInit{ 
    constructor() {}; 
    ngOnInit() { 
     this.test(); 
    } 
    abstract test(); 
} 

父HTML:

<div id="main"> 
<div class="container pad-top"> 
    <div class="row"> 
    <div class="col-xs-12 nopadding text-center"> 
     <a [routerLink]="['/events/vote-events']"><img class="img-responsive sin-looks-votacion" 
                src="assets/images/no-tienes-votaciones.jpg"></a> 
    </div> 
    </div> 
</div> 

而且我想这样做:

子组件:

export class MyVotesComponent extends EventsComponent { 

    private potato; 

    constructor() { 
     super(); 
    } 

    test() { 
     console.log("Testttttttttttt"); 
    } 
} 

子html:

<app-events></app-events> 

的事情是,我不得不从events.module.ts声明删除EventsComponent。现在浏览器会抛出:

'app-events' is not a known element: 

最后一个问题是:这是最好的方法吗?如果不是,会是什么?我应该读什么?如果这确实是最好的方法,我错过了什么?

在此先感谢。

一切顺利,

亚历

+1

为什么要扩展组件? – Aravind

+0

我不是100%以下...也许是'ng-content'或'@ ContentChildren'的用例吗? – Jeff

+0

@Aravind我想扩展父组件,以避免子组件中的重复代码。 @Jeff请你再详细说明一下吗? “@ ContentChildren”或“ng-content”会做什么。谢谢! – abullrich

回答

0

我认为你必须复制的templateUrlstyleUrls@Component装饰每个子类的。但至少你可以保持这些文件在同一个地方:

@Component({ 
    selector: 'my-votes', 
    templateUrl: './events.component.html', 
    styleUrls: ['./events.component.css'] 
}) 
export class MyVotesComponent extends EventsComponent { 

    private potato; 

    constructor() { 
     super(); 
    } 

    test() { 
     console.log("Testttttttttttt"); 
    } 
} 

你可能会想从你的抽象基类中删除@Component装饰。

+0

我会试一试,这绝对值得一试。谢谢! – abullrich

+0

好的,抱歉我的答案延迟。我在周末外出,没有时间捣鼓代码。这确实解决了我的问题,并能够成功地重新使用相同的html和父组件。干杯! – abullrich