Table of Contents
1. Project a piece of content" >1. Project a piece of content
2. Project multiple pieces of content/components" >2. Project multiple pieces of content/components
使用标签锁定投影位置
" >##3. Projection of child elements
" >4. Conditional content projection
" >5. @ContentChild & @ContentChildren
" >6. @ViewChild & @ViewChildren
Home Web Front-end JS Tutorial A brief analysis of content projection in Angular component learning

A brief analysis of content projection in Angular component learning

Aug 09, 2021 am 10:24 AM
angular components

This article will take you through the content projection in Angular components. Content projection is very similar to the slot in Vue. It is very useful when encapsulating components. Let’s experience it together

A brief analysis of content projection in Angular component learning

[Related tutorial recommendations: "angular tutorial 》】

1. Project a piece of content

The container component is written like this

<div>
  编号1
  <ng-content></ng-content>
</div>
Copy after login

Business components are used like this

<app-page-container>
	未指定投影位置的内容会被投影到无select属性的区域
</app-page-container>
Copy after login

2. Project multiple pieces of content/components

Container components are used like this Write

  • Use tag to lock the projection position

  • Use class to lock the projection position

  • Lock the projection position with a custom component name

  • Lock the projection position with a custom attribute

<div>
  编号2
  <ng-content select="h3"></ng-content>
  <ng-content select=".my-class"></ng-content>
  <ng-content select="app-my-hello"></ng-content>
  <ng-content select="[content]"></ng-content>
</div>
Copy after login

Business components are used like this

<app-page-container>
  <h3 id="使用标签锁定投影位置">使用标签锁定投影位置</h3>
  <div class="my-class">使用class锁定投影位置</div>
  <app-my-hello>使用自定义组件名称锁定投影位置</app-my-hello>
  <div content>使用自定义属性锁定投影位置</div>
</app-page-container>
Copy after login

Demo

A brief analysis of content projection in Angular component learning

##3. Projection of child elements

Use

ng-container to wrap child elements and reduce unnecessary dom layers, similar to the template in vue

The container component is written like this

<div>
  编号4
  <ng-content select="question"></ng-content>
</div>
Copy after login

Business components are written like this

<app-page-container>
  <ng-container ngProjectAs="question">
    <p>内容投影酷吗?</p>
    <p>内容投影酷吗?</p>
    <p>内容投影酷吗?</p>
    <p>内容投影酷吗?</p>
  </ng-container>
</app-page-container>
Copy after login

4. Conditional content projection

Chinese website description:

  • If your component needs to_

    conditionally_render content or render content multiple times, you should configure the component to Accepts an ng-template element containing content to be conditionally rendered.

  • In this case, it is not recommended to use the ng-content element because as long as the user of the component provides the content, even if the component never defines the ng-content element or the ng- The content element is located inside the

    ngIf statement, and the content is always initialized.

  • Using the ng-template element, you can have the component explicitly render content based on any conditions you want, and render it multiple times. Angular does not initialize the content of an ng-template element until the element is explicitly rendered.

Use ng-containerDefine our projection block

  • Use

    ngTemplateOutlet directive to render ng-template elements.

  • Use the built-in dynamic directive

    *ngIf to control whether to render the projection.

  • <div>
      编号3
      <ng-content select="[button]"></ng-content>
      <p *ngIf="expanded">
        <ng-container [ngTemplateOutlet]="content.templateRef"> </ng-container>
      </p>
    </div>
    Copy after login

In the business component we use ng-template to wrap our actual elements.

my-hello component only does log output in ngOnInit() to observe the printing situation.

<app-page-container>
  <div button>
    <button appToggle>切换</button>
  </div>
  <ng-template appContent>
    <app-my-hello>有条件的内容投影~</app-my-hello>
  </ng-template>
</app-page-container>
Copy after login

Now you will find that the page does not render normally as smoothly as before, because our logic has not been colluded yet, let's continue. Create a command and register it in NgModule. You must register before you can use it~

The command needs to be registered~

import { Directive, TemplateRef } from &#39;@angular/core&#39;;

@Directive({
  selector: &#39;[appContent]&#39;,
})
export class ContentDirective {
  constructor(public templateRef: TemplateRef<unknown>) {}
}
Copy after login

We will define it again A command to control the display/hiding of the logo in the component

The command needs to be registered~

@Directive({
  selector: &#39;[appToggle]&#39;,
})
export class ToggleDirective {
  @HostListener(&#39;click&#39;) toggle() {
    this.app.expanded = !this.app.expanded;
  }
  constructor(public app: PageContainerComponent) {}
}
Copy after login

State the definition just now in our container component Content instructions, the page currently does not report an error~

export class PageContainerComponent implements OnInit {

  expanded: boolean = false;

  @ContentChild(ContentDirective)
  content!: ContentDirective;

}
Copy after login

You can see from the log that when we switch the expanded logo of the container component, there is only the open state The my-hello component will be initialized. Although the following ngIf cannot see the rendered content on the page, the component has actually been initialized.

<div *ngIf="false">
  <ng-content *ngIf="false" select="app-my-hello"></ng-content>
</div>
Copy after login

5. @ContentChild & @ContentChildren

Use these two decorators to project the components Perform the operation

Use annotations to define the projected component in the business component

@ContentChild(HelloWorldComp)
helloComp: HelloWorldComp;

@ContentChildren(HelloWorldComp)
helloComps: QueryList<HelloWorldComp>;
Copy after login

Execute in thengAfterContentInit()hook Then operate the projected component

6. @ViewChild & @ViewChildren

##Use these two decorators To operate finger-joined sub-components

Use annotations to define sub-components in business components

@ViewChild(HelloWorldComp)
helloComp: HelloWorldComp;
  
@ViewChildren(HelloWorldComp)
helloComps QueryList<HelloWorldComp>;
Copy after login
In

ngAfterViewInit()After the hook is executed, operate the direct sub-component

Conclusion

We have just written here about the use of components. Our writing skills are limited, so come on. Got~

For more programming-related knowledge, please visit: Introduction to Programming! !

The above is the detailed content of A brief analysis of content projection in Angular component learning. 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 the Windows 10 old version component DirectPlay How to install the Windows 10 old version component DirectPlay Dec 28, 2023 pm 03:43 PM

Many users always encounter some problems when playing some games on win10, such as screen freezes and blurred screens. At this time, we can solve the problem by turning on the directplay function, and the operation method of the function is also Very simple. How to install directplay, the old component of win10 1. Enter "Control Panel" in the search box and open it 2. Select large icons as the viewing method 3. Find "Programs and Features" 4. Click on the left to enable or turn off win functions 5. Select the old version here Just check the box

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

How to implement calendar component using Vue? How to implement calendar component using Vue? Jun 25, 2023 pm 01:28 PM

Vue is a very popular front-end framework. It provides many tools and functions, such as componentization, data binding, event handling, etc., which can help developers build efficient, flexible and easy-to-maintain Web applications. In this article, I will introduce how to implement a calendar component using Vue. 1. Requirements analysis First, we need to analyze the requirements of this calendar component. A basic calendar should have the following functions: display the calendar page of the current month; support switching to the previous month or next month; support clicking on a certain day,

VUE3 development basics: using extends to inherit components VUE3 development basics: using extends to inherit components Jun 16, 2023 am 08:58 AM

Vue is one of the most popular front-end frameworks currently, and VUE3 is the latest version of the Vue framework. Compared with VUE2, VUE3 has higher performance and a better development experience, and has become the first choice of many developers. In VUE3, using extends to inherit components is a very practical development method. This article will introduce how to use extends to inherit components. What is extends? In Vue, extends is a very practical attribute, which can be used for child components to inherit from their parents.

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.

How to open the settings of the old version of win10 components How to open the settings of the old version of win10 components Dec 22, 2023 am 08:45 AM

Win10 old version components need to be turned on by users themselves in the settings, because many components are usually closed by default. First we need to enter the settings. The operation is very simple. Just follow the steps below. Where are the win10 old version components? Open 1. Click Start, then click "Win System" 2. Click to enter the Control Panel 3. Then click the program below 4. Click "Enable or turn off Win functions" 5. Here you can choose what you want to open

See all articles