Table of Contents
1. ng-content Content projection
二、 有条件的内容投影
Home Web Front-end JS Tutorial Let's talk about the method of content projection in angular

Let's talk about the method of content projection in angular

May 12, 2022 am 10:41 AM
angular angular.js

This article will talk about content projection in angular, introduce the method of using ng-content for content projection, and understand the implementation method of conditional content projection. I hope it will be helpful to everyone. !

Let's talk about the method of content projection in angular

1. ng-content Content projection

1.1 <span style="font-size: 16px;">ng-content</span>

ng-content element is a placeholder used to insert external or dynamic content symbol. The parent component passes external content to the child component. When Angular parses the template, the external content will be inserted in the child component template where ng-content appears. . [Related tutorial recommendations: "angular tutorial"]

We can use content projection to create reusable components. These components have similar logic and layout and can be used in many places. Generally we often use it when encapsulating some public components.

1.2 Why use content projection

Define a button component:

button-component.ts

@Component({
    selector: &#39;[appButton]&#39;,
    template: `
    <span class="icon-search"></span>
`
})
export class AppButtonComponent {}
Copy after login

The purpose of this button component is to add a search icon inside the button. We actually use it as follows:

<button appButton>click</button>
Copy after login
Copy after login

We found that the component will only display the search icon, and the text of the button will not be displayed. , you may think of the most commonly used @Input decorator, but what if we don’t just want to pass in text, but a paragraph of html? ng-content will be used at this time.

1.3 Single Slot Content Projection

The most basic form of content projection is Single Slot Content Projection.

Single-slot content projection refers to creating a component into which we can project a component.

Take the button component as an example to create a single-slot content projection:

button-component.ts

@Component({
    selector: &#39;[appButton]&#39;,
    template: `
    <span class="icon-search"></span> <ng-content></ng-content>
`
})
export class AppButtonComponent {}
Copy after login

The actual usage is as follows:

<button appButton>click</button>
Copy after login
Copy after login

It can be found that the effect of this button component is to display both the search icon and the text of the button (click). That is, the content in the middle of is projected to the <ng-content></ng-content> Location. The

ng-content element is a placeholder, it does not create a real DOM element. Those custom attributes of ng-content will be ignored.

1.4 Multi-slot content projection

A component can have multiple slots, each A slot can specify a CSS selector, which determines what content goes into the slot. This mode is called Multi-Slot Content Projection. Using this mode, we must specify the position where we want the projected content to appear. This can be accomplished by using the select attribute of ng-content.

  • The component template contains multiple ng-content tags.
  • In order to distinguish the projected content that can be projected to the corresponding ng-content tag, you need to use the select attribute on the ng-content tag as identification .
  • select Attributes support tag name, property, CSS class and :not pseudo-class## Any combination of #.
  • A
  • ng-content tag that does not add the select attribute will serve as the default slot. All unmatched projected content will be projected at this ng-content location.
Take the button component as an example to create a multi-slot content projection:

button-component.ts

@Component({
    selector: &#39;[appButton]&#39;,
    template: `
    <span class="icon-search"></span> <ng-content select="[shuxing]"></ng-content> <ng-content select="p"></ng-content> <ng-content select=".lei"></ng-content>
`
})
export class AppButtonComponent {}
Copy after login

The actual usage is as follows:

<button appButton>
<p>click</p> <span shuxing>me</span> <span class="lei">here</span>
</button>
Copy after login

1.5 ngProjectAs<span style="font-size: 16px;"></span>

In some cases, we need to use

ng-container Wrap some content and pass it to the component. Most of the time it's because we need to use structural directives like ngIf or ngSwitch etc. .

In the example below, we wrap

header in ng-container.

@Component({
    selector: &#39;app-card&#39;,
    template: `
		<div class="card">
		  <div class="header">
		    <ng-content select="header"></ng-content>
		  </div>
		  <div class="content">
		    <ng-content select="content"></ng-content>
		  </div>
		  <div class="footer">
		    <ng-content select="footer"></ng-content>
		  </div>
		  <ng-content></ng-content>
		</div>
`
})
export class AppCardComponent {}
Copy after login

Usage:

<app-card>
  <ng-container>
    <header>
      <h1>Angular</h1>
    </header>
  </ng-container>
  <content>One framework. Mobile & desktop.</content>
  <footer><b>Super-powered by Google </b></footer>
</app-card>
Copy after login

Due to the existence of

ng-container, the header part is not rendered into the slot we want to render. , instead it is rendered into ng-content which does not provide any selector. In this case we can use the
ngProjectAs attribute. Add this attribute to
ng-container above, and you can render it according to our expectations.

<app-card>
  <ng-container ngProjectAs=&#39;header&#39;>
    <header>
      <h1>Angular</h1>
    </header>
  </ng-container>
  <content>One framework. Mobile & desktop.</content>
  <footer><b>Super-powered by Google </b></footer>
</app-card>
Copy after login

二、 有条件的内容投影

如果你的元件需要有条件地渲染内容或多次渲染内容,则应配置该元件以接受一个 ng-template 元素,其中包含要有条件渲染的内容。

在这种情况下,不建议使用 ng-content 元素,因为只要元件的使用者提供了内容,即使该元件从未定义 ng-content 元素或该 ng-content 元素位于 ngIf 语句的内部,该内容也总会被初始化。

使用 ng-template 元素,你可以让元件根据你想要的任何条件显式渲染内容,并可以进行多次渲染。在显式渲染 ng-template 元素之前,Angular 不会初始化该元素的内容。

2.1 <span style="font-size: 16px;">ng-container</span>

既不是一个组件,也不是一个指令,仅仅是一个特殊的tag而已。 使用 ng-container 渲染所包含的模板内容,不包含自身。

  • angular代码片段
<div>
  <ng-container>
    <p>My name is wyl.</p>
    <p>What is you name?</p>
  </ng-container>
</div>
Copy after login
  • 浏览器调试窗口,可以发现 <ng-container> 标签消失了,并没有起任何作用
<div>
  <p>My name is wyl.</p>
  <p>What is you name?</p>
</div>
Copy after login
  • 使用场景,如下,在我们需要遍历if 判断 时,它可以承担一个载体的作用
<ul>
  <ng-container *ngFor="let item of items">
    <li>{{ item .name}}</li>
    <li>{{ item .age}}</li>
    <li>{{ item .sex}}</li>
  </ng-container>
</ul>
Copy after login

另外,ng 中常见错误之一的 forif 不能写在同一标签上(在一个宿主元素上只能应用一个结构型指令),利用 ng-container 标签可以在实现功能的基础上减少层级的嵌套。

2.2 <span style="font-size: 16px;">ng-template</span>

先来看下面一段代码

<ng-template>
    <p> In template, no attributes. </p>
</ng-template>

<ng-container>
    <p> In ng-container, no attributes. </p>
</ng-container>
Copy after login

浏览器输出结果是:

In ng-container, no attributes.
Copy after login

<ng-template> 中的内容不会显示。当在上面的模板中添加 ngIf 指令:

<ng-template [ngIf]="true">
   <p> ngIf with a ng-template.</p>
</ng-template>

<ng-container *ngIf="true">
   <p> ngIf with an ng-container.</p>
</ng-container>
Copy after login

浏览器输出结果是:

ngIf with a ng-template.
ngIf with an ng-container.
Copy after login

2.3 <span style="font-size: 16px;">ng-template</span><ng-container> 的配合使用

<ng-container *ngIf="showSearchBread; else tplSearchEmpty">
     暂时搜索不到您要的数据喔
</ng-container>
<ng-template #tplSearchEmpty>
     快快开始获取吧!
</ng-template>
Copy after login

2.4 <span style="font-size: 16px;">ngTemplateOutlet</span>

插入 ng-template 创建的内嵌视图。 ngTemplateOutlet 是一个结构型指令,接收一个 TemplateRef 类型的值;

<div *ngTemplateOutlet="tpl1"></div>
<ng-template #tpl1>
  <span>I am span in template {{title}}</span>
</ng-template>
Copy after login

*ngTemplateOutlet = "templateRefExp; content: contentExp "

  • templateRefExp: ng-template 元素的 #ID
  • contextExp:
    • 可空参数

    • content 是一个对象,这个对象可以包含一个 $implicitkey 作为默认值, 使用时在 模板 中用 let-key 语句进行绑定

    • content 的非默认字段需要使用 let-templateKey=contentKey 语句进行绑定

使用如下:

@Component({
  selector: &#39;ng-template-outlet-example&#39;,
  template: `
    <ng-container *ngTemplateOutlet="greet"></ng-container>
    <hr>
    <ng-container *ngTemplateOutlet="eng; context: myContext"></ng-container>
    <hr>
    <ng-container *ngTemplateOutlet="svk; context: myContext"></ng-container>
    <hr>
    <ng-template #greet><span>Hello</span></ng-template>
    <ng-template #eng let-name><span>Hello {{name}}!</span></ng-template>
    <ng-template #svk let-person="localSk"><span>Ahoj {{person}}!</span></ng-template>
`
})
class NgTemplateOutletExample {
  myContext = {$implicit: &#39;World&#39;, localSk: &#39;Svet&#39;};
}
Copy after login

2.5 利用 <span style="font-size: 16px;">ngTemplateOutlet</span> 进行内容投影

@Component({
    selector: &#39;app-card&#39;,
    template: `
		<div class="card">
		  <div class="header">
		  	<ng-container *ngTemplateOutlet="headerTemplate; context: { $implicit: title, index: otherDate }"></ng-container>
		  </div>
		</div>
`
})
export class AppCardComponent {

	@ContentChild(&#39;header&#39;, { static: true }) headerTemplate: TemplateRef<any>;

	public title = &#39;Test&#39;;
	public otherDate = {
	 	auth: &#39;me&#39;,
	 	name: &#39;appCard&#39;
	};
}
Copy after login

使用

<app-card>
  <ng-template #header let-label let-item="otherDate">
    <h1>Angular</h1> {{label}} (Test) and  {{otherDate | json}} ({auth: &#39;me&#39;, name: &#39;appCard&#39;})
  </ng-template>
</app-card>
Copy after login

更多编程相关知识,请访问:编程教学!!

The above is the detailed content of Let's talk about the method of content projection in angular. 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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Angular learning talks about standalone components (Standalone Component) Angular learning talks about standalone components (Standalone Component) Dec 19, 2022 pm 07:24 PM

This article will take you to continue learning angular and briefly understand the standalone component (Standalone Component) in Angular. I hope it will be helpful to you!

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

Detailed explanation of angular learning state manager NgRx Detailed explanation of angular learning state manager NgRx May 25, 2022 am 11:01 AM

This article will give you an in-depth understanding of Angular's state manager NgRx and introduce how to use NgRx. I hope it will be helpful to you!

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!

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 + NG-ZORRO quickly develop a backend system Angular + NG-ZORRO quickly develop a backend system Apr 21, 2022 am 10:45 AM

This article will share with you an Angular practical experience and learn how to quickly develop a backend system using angualr combined with ng-zorro. I hope it will be helpful to everyone!

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 independent components in Angular and see how to use them A brief analysis of independent components in Angular and see how to use them Jun 23, 2022 pm 03:49 PM

This article will take you through the independent components in Angular, how to create an independent component in Angular, and how to import existing modules into the independent component. I hope it will be helpful to you!

See all articles