Table of Contents
Introduction to ng-template directive
Introduction to the ng-container directive
ng-container usage
ng-template usage
Home Web Front-end JS Tutorial A brief discussion on Angular template directives: usage of ng-template and ng-container

A brief discussion on Angular template directives: usage of ng-template and ng-container

Aug 05, 2021 am 10:38 AM
angular template

This article will give you a brief introduction to the ng-template and ng-container directives of the Angular template, and introduce how to use the ng-template and ng-container directives.

A brief discussion on Angular template directives: usage of ng-template and ng-container

Introduction to ng-template directive

ng-template is an Angular structural directive used to render HTML. It is never shown directly. In fact, Angular replaces the ng-template and its contents with an annotation before rendering the view. [Related tutorial recommendation: "angular tutorial"]

If you do not use structural directives and just wrap some other elements into ng-template, those elements will be invisible.

Instructions like *ngFor and *ngIf will internally translate these attributes into an element in Angular and use it to wrap the host element.

Introduction to the ng-container directive

To avoid creating extra divs, we can use ng-container instead, which is a grouping element, but it does not pollute the style Or element layout, because Angular won't put it into the DOM at all. ng-container is a syntax element that is recognized and processed by the Angular parser. It's not a directive, component, class, or interface, but more like the curly braces in an if block in JavaScript.

ng-container usage

Usage 1 (the most basic usage)

We are here There are some judgments to be made when writing in a list loop. We know that angular's structural instructions do not allow two to exist at the same time. At this time, if we do not want to add extra divs, we can use ng-container

<ul>
    <ng-container *ngFor="let item of list">
        <li *ngIf="item.context">{{item.context}}</li>
    </ng-container>
</ul>
Copy after login

Usage 2 (used in combination with ngSwitch)

<ng-container [ngSwitch]="type">
    <ng-container *ngSwitchCase="&#39;title&#39;">标题</ng-container>
    <ng-container *ngSwitchCase="&#39;text&#39;">内容</ng-container>
    <ng-container *ngSwitchDefault>其他</ng-container>
</ng-container>
Copy after login

Of course, ngSwitch can also be written directly on the html tag.

Usage three (used in conjunction with ng-template)

can be used in conjunction with template to extract duplicate module content, or to pass Specifies the template to be displayed. For example, in the following example, Party A has Party A’s name and introduction, and Party B also has these introductions, so we can integrate the joint introductions.

<div>
    <!--甲方-->
    <div>
        <div class="left">甲方:</div>
        <div class="right">
            甲方姓名
            <ng-container *ngTemplateOutlet="introduce; context: {data: data.partyA}"></ng-container>
            <!--也可以写成这种方式-->
            <!--
            <ng-container [ngTemplateOutlet]="introduce"
                [ngTemplateOutletContext]="{data: data.partyA}">
            </ng-container>
            [ngTemplateOutlet]也可用在ng-template上
            -->
        </div>
    </div>
    <!--乙方-->
    <div>
        <div class="left">乙方:</div>
        <div class="right">
            乙方姓名
            <ng-container *ngTemplateOutlet="introduce; context: {data: data.partyB}"></ng-container>
        </div>
    </div>
    <!--let-data="data"就是上面传进来的值-->
    <ng-template #introduce let-data="data">
        <p>合同介绍......</p>
    </ng-template>
</div>
Copy after login

ngTemplateOutlet is a string that defines the template reference and the context (i.e. ng-template) object of the template, so if there are multiple template references, you can use this method ngTemplateOutletContext is the context (i.e. ng-template) object EmbeddedViewRef attached to. This should be an object whose keys can be used for bindings declared by the local template let. Using $implicit a key in a context (i.e. ng-template) object will set its value to the default value. ngTemplateOutlet can also be used for templates passed in from the outside

child.component.html

<ng-template [ngTemplateOutlet]="tplRef" [ngTemplateOutletContext]="{data: data}"></ng-template>
Copy after login

child.component.ts

@Input() tplRef: TemplateRef<any>
Copy after login

ng-template usage

##Usage 1

Used in conjunction with *ngIf, this eliminates the need to add two different judgments Condition, you can use if else statement directly in html

<div *ngIf="text; else noData">{{text}}</div>
<ng-template #noData>
    <div class="gary">暂无数据</div>
</ng-template>
Copy after login

Usage 2

When using antd's modalService to create a dialog box in the page, you can The template is written in html, loaded by reference and placed in the modal's nzContent (it's a bit confusing, look at the code)

<ng-tempalte #content>xxxxxxx</ng-template>
Copy after login
export class AppComponent implements OnInit {
    // 引入模板
     @ViewChild(&#39;content&#39;) contentTpl: TemplateRef<any>;
    ngOnInit() {
        this.modalService.create({
            nzTitle: &#39;标题&#39;,
            nzContent: this.contentTpl
        })
    }
}
Copy after login

Usage three

Pass it to the component as an input variable in the form of a template, so that we can write what we want when using this component. For example, if we write a shared component that has no data yet, we usually only need to pass text. In some special cases, we may need to add some new buttons.

empty.component.html

<div>
    <img src=""/>
    <div>
        <ng-container [ngSwitch]="true">
            <ng-container *ngSwitchCase="isTemplate(text)"
                [ngTemplateOutlet]="text"
            ></ng-container>
        </ng-container>
        {{text || &#39;&#39;}}
    </div>
</div>
Copy after login

empty.component.ts

export class EmptyComponent {
    @Input() text: TemplateRef<any>
  isTemplate(text: any) {
      return text instanceof TemplateRef;
  }
}
Copy after login
Summary, these are some of the most basic Usage, these are the usages that I know now. If you know more, you are welcome to add.

For more programming related knowledge, please visit:

Programming Video! !

The above is the detailed content of A brief discussion on Angular template directives: usage of ng-template and ng-container. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to install Angular on Ubuntu 24.04 How to install Angular on Ubuntu 24.04 Mar 23, 2024 pm 12:20 PM

Angular.js is a freely accessible JavaScript platform for creating dynamic applications. It allows you to express various aspects of your application quickly and clearly by extending the syntax of HTML as a template language. Angular.js provides a range of tools to help you write, update and test your code. Additionally, it provides many features such as routing and form management. This guide will discuss how to install Angular on Ubuntu24. First, you need to install Node.js. Node.js is a JavaScript running environment based on the ChromeV8 engine that allows you to run JavaScript code on the server side. To be in Ub

An article exploring server-side rendering (SSR) in Angular An article exploring server-side rendering (SSR) in Angular Dec 27, 2022 pm 07:24 PM

Do you know Angular Universal? It can help the website provide better SEO support!

How to use PHP and Angular for front-end development How to use PHP and Angular for front-end development May 11, 2023 pm 04:04 PM

With the rapid development of the Internet, front-end development technology is also constantly improving and iterating. PHP and Angular are two technologies widely used in front-end development. PHP is a server-side scripting language that can handle tasks such as processing forms, generating dynamic pages, and managing access permissions. Angular is a JavaScript framework that can be used to develop single-page applications and build componentized web applications. This article will introduce how to use PHP and Angular for front-end development, and how to combine them

A brief analysis of how to use monaco-editor in angular A brief analysis of how to use monaco-editor in angular Oct 17, 2022 pm 08:04 PM

How to use monaco-editor in angular? The following article records the use of monaco-editor in angular that was used in a recent business. I hope it will be helpful to everyone!

Angular components and their display properties: understanding non-block default values Angular components and their display properties: understanding non-block default values Mar 15, 2024 pm 04:51 PM

The default display behavior for components in the Angular framework is not for block-level elements. This design choice promotes encapsulation of component styles and encourages developers to consciously define how each component is displayed. By explicitly setting the CSS property display, the display of Angular components can be fully controlled to achieve the desired layout and responsiveness.

Let's talk about how to customize the angular-datetime-picker format Let's talk about how to customize the angular-datetime-picker format Sep 08, 2022 pm 08:29 PM

How to customize the angular-datetime-picker format? The following article talks about how to customize the format. I hope it will be helpful to everyone!

A step-by-step guide to understanding dependency injection in Angular A step-by-step guide to understanding dependency injection in Angular Dec 02, 2022 pm 09:14 PM

This article will take you through dependency injection, introduce the problems that dependency injection solves and its native writing method, and talk about Angular's dependency injection framework. I hope it will be helpful to you!

PHP email templates: customize and personalize your email content. PHP email templates: customize and personalize your email content. Sep 19, 2023 pm 01:21 PM

PHP email templates: Customize and personalize your email content With the popularity and widespread use of email, traditional email templates can no longer meet people's needs for personalized and customized email content. Now we can create customized and personalized email templates by using PHP programming language. This article will show you how to use PHP to achieve this goal, and provide some specific code examples. 1. Create an email template First, we need to create a basic email template. This template can be an HTM

See all articles