I am wondering if it's possible to take the html (and directives) that are already in one component's template and include them in some way in another component's template. This would be useful where one would be extending an existing component and would like to use its existing template but add some additional html/directives.
In Twig (a popular php templating library) for example it's possible to extend a template:
{% extends "base.html" %}
{% block title %}Index{% endblock %}
{% block head %}
{{ parent() }}
<style type="text/css">
.important { color: #336699; }
</style>
{% endblock %}
{% block content %}
<h1>Index</h1>
<p class="important">
Welcome on my awesome homepage.
</p>
{% endblock %}
Is there any such thing like this in Angular 2? Again I'm not looking to embed an existing component but instead extend one.
Typescript and Angular give you a way to handle this encapsulation. Inherited components! Using class inheritance in TypeScript, you can declare a base component that contains common UI functionality and use it to extend any standard component you'd like.
You can simply extend your base component and overwrite the template. This allows you to have different components with the exact same functionality, but different templates. Save this answer.
A template is a form of HTML that tells Angular how to render the component. Views are typically organized hierarchically, allowing you to modify or show and hide entire UI sections or pages as a unit. The template immediately associated with a component defines that component's host view.
Written in TypeScript, Angular makes it possible to use the concept of inheritance in our components.
If you have a chunk of html inside template tags, you can use ngTemplateOutlet
without having to create a new component:
https://angular.io/api/common/NgTemplateOutlet
You could probably come up with a creative way of sharing the templates so that they are usable by multiple components.
For instance, a parent could acquire the TemplateRef
using a ViewChild
, then pass that in to an Input
property on a child component.
You can find more information about those techniques here:
http://blog.angular-university.io/angular-ng-template-ng-container-ngtemplateoutlet/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With