search
HomeWeb Front-endJS TutorialA brief analysis of content projection in Angular component learning

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>

Business components are used like this

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

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>

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>

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>

Business components are written like this

<app-page-container>
  <ng-container>
    <p>内容投影酷吗?</p>
    <p>内容投影酷吗?</p>
    <p>内容投影酷吗?</p>
    <p>内容投影酷吗?</p>
  </ng-container>
</app-page-container>

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>

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>

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>) {}
}

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) {}
}

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;

}

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>

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>;

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>;

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
This article is reproduced at:掘金社区. If there is any infringement, please contact admin@php.cn delete
C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

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.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

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 the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

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 vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

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.

See all articles

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

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version