加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

在Angular2中使用父组件的模板

发布时间:2020-12-17 06:59:45 所属栏目:安全 来源:网络整理
导读:我想在Angular中使用组件的继承继承父模板. 介绍 我有一些基本组件(让我们称之为ParentComponent)和该组件的几个子组件(Child1Component和Child2Component).我想将默认行为放在ParentComponent中,然后在子组件中设置/扩展此行为. ParentComponent模板已包含
我想在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装饰器不能部分继承,它全有或全无.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读