【发布时间】:2019-12-30 18:46:46
【问题描述】:
问题(Angular 7)
我希望能够在不重写整个模板的情况下“修改”被覆盖组件的模板,这意味着它将与它所覆盖的组件共享相同的 html 模板。目标是能够自定义组件,并且覆盖组件模板上的任何更改都将直接反映在覆盖组件中。
也许我们可以说我想在两个组件之间共享部分逻辑和模板。
当前实现示例
@Component({
selector: 'component-a',
templateUrl: './component-a.html'
})
export class ComponentAComponent {
constructor() { }
}
@Component({
selector: 'component-a',
templateUrl: './component-a2.html'
})
export class ComponentA2Component extends ComponentAComponent {
specificStuff = 'I am additional stuff';
constructor() { }
}
component-a2.component.html
...
[ same as beginning of component-a.component.html]
...
<!-- Some specific stuff like an additional label, button, mat form field -->
<div>
{{ specificStuff }}
</div>
...
[ same as end of component-a.component.html]
...
如我们所见,如果我更改component-a.html,它不会影响componentA2。
目标
目标是两个组件使用相同的模板,但最终(编译)DOM 会有所不同。我不想用 ngIf 做这个。
类似
@Component({
selector: 'component-a',
templateUrl: './component-a.html'
})
export class ComponentAComponent {
public specificStuff;
constructor() { }
}
@Component({
selector: 'component-a',
templateUrl: './component-a.html'
})
export class ComponentA2Component extends ComponentAComponent {
public name = 'World';
public specificStuff = '<div> Hello {{name}} </div>';
constructor() { }
}
组件-a.component.html
<div>Yo</div>
<ng-template #specificStuff></ng-template>
<div>Bye</div>
组件A的结果模板:
<div>Yo</div>
<ng-template #specificStuff></ng-template>
<div>Bye</div>
componentA2 的结果模板:
<div>Yo</div>
<ng-template #specificStuff><div> Hello {{name}} </div></ng-template>
<div>Bye</div>
我看到了什么
innerHTML: 不适用于角度插值、指令等。
ngComponentOutlet: 需要创建另一个组件并处理上下文 + 我想避免在组件选择器中包含一个层以避免破坏样式
ngTemplateOutlet: 模板仍然需要以某种方式传递吗? (也许这是我需要但不知道如何使用它)
【问题讨论】:
-
如果我没记错的话,我仍然需要更改注入我的组件的组件的模板才能设置内容,所以我也需要“覆盖”这个组件。这不是我真正想要的。我希望能够从组件本身“自定义”组件。
-
如果不完全重写模板,您将无法做到这一点。想想 Angular 在运行时对你的模板有什么了解(如果你做 AOT)。
-
不可能是一个可以接受的答案。我想我在研究之后真正需要的是某种东西,比如 pug、nunjucks、带有模板继承的 EJS。非常感谢您的建议。
标签: angular overriding angular2-template