


A brief discussion on Angular template directives: usage of ng-template and ng-container
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.
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>
Usage 2 (used in combination with ngSwitch)
<ng-container [ngSwitch]="type"> <ng-container *ngSwitchCase="'title'">标题</ng-container> <ng-container *ngSwitchCase="'text'">内容</ng-container> <ng-container *ngSwitchDefault>其他</ng-container> </ng-container>
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>
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></ng-template>
child.component.ts
@Input() tplRef: TemplateRef<any></any>
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>{{text}}</div> <ng-template> <div>暂无数据</div> </ng-template>
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>
export class AppComponent implements OnInit { // 引入模板 @ViewChild('content') contentTpl: TemplateRef<any>; ngOnInit() { this.modalService.create({ nzTitle: '标题', nzContent: this.contentTpl }) } }
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=""/ alt="A brief discussion on Angular template directives: usage of ng-template and ng-container" > <div> <ng-container [ngSwitch]="true"> <ng-container *ngSwitchCase="isTemplate(text)" [ngTemplateOutlet]="text" ></ng-container> </ng-container> {{text || ''}} </div> </div>
empty.component.ts
export class EmptyComponent { @Input() text: TemplateRef<any> isTemplate(text: any) { return text instanceof TemplateRef; } }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!

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver Mac version
Visual web development tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

SublimeText3 Mac version
God-level code editing software (SublimeText3)