Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to extend a Template in Angular 2?

Tags:

angular

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.

like image 219
jcroll Avatar asked Aug 02 '17 15:08

jcroll


People also ask

Can you extend an Angular component?

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.

Can a component have multiple templates Angular?

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.

What is correct about template in Angular?

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.

Is there inheritance in Angular?

Written in TypeScript, Angular makes it possible to use the concept of inheritance in our components.


1 Answers

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/

like image 112
chrispy Avatar answered Sep 21 '22 19:09

chrispy