微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在Angular2中使用父组件的模板

我想在Angular中使用组件的继承继承父模板.

介绍

我有一些基本组件(让我们称之为ParentComponent)和该组件的几个子组件(Child1Component和Child2Component).我想将认行为放在ParentComponent中,然后在子组件中设置/扩展此行为. ParentComponent模板已包含所有需要的东西,因此我希望子组件认使用此模板.

实现的第一个变体(不起作用,错误:没有为组件Child1Component指定模板):

@Component({
    selector: 'app-parent',templateUrl: './app-parent.component.html',styleUrls: ['./app-parent.component.scss']
})
export class ParentComponent {
}

@Component({
    selector: 'app-child1'
})
export class Child1Component extends ParentComponent {
}


@Component({
    selector: 'app-child2'
})
export class Child2Component extends ParentComponent {
}

我发现我可以将子模板的templateUrl和styleUrls设置为父模板,但只有在子项的ViewEncapsulation设置为None时它才有效.

第二个变种(它有效,但我不喜欢它):

@Component({
    selector: 'app-parent',styleUrls: ['./app-parent.component.scss']
})
export class ParentComponent {
}

@Component({
    selector: 'app-child1',templateUrl: '../parent/app-parent.component.html',styleUrls: ['../parent/app-parent.component.scss'],encapsulation: ViewEncapsulation.None
})
export class Child1Component extends ParentComponent {
}

@Component({
    selector: 'app-child2',encapsulation: ViewEncapsulation.None
})
export class Child2Component extends ParentComponent {
}

我不喜欢这种解决方案的原因

>子组件中没有视图封装;
>每个子组件的模板和样式URL复制粘贴.

能否请你为这项任务建议更好的解决方案?

解决方法

第二种方法是唯一可能的方法,因为有装饰器继承的规则,见 https://github.com/angular/angular/issues/11606.

@Component装饰器不能部分继承,它全有或全无.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐