What is the difference between ng-template and ng-content in Angular?

In Angular, ng-template and ng-content are both directives used to manage and display content, but they have some differences in usage and functionality. Let me explain the difference for you and provide some examples to illustrate.

ng-template:
ng-template is a container for defining reusable templates. It will not be rendered into any actual element itself, but is used to wrap a piece of HTML code for reference by other directives or components. Usually used with structural directives (such as *ngIf, *ngFor, etc.) to define template content.

Example:

<ng-container *ngFor="let item of items">
  <ng-template let-item>
    <div>{
    
    {
    
     item.name }}</div>
  </ng-template>
</ng-container>

In the example above, ng-template defines a template for iterating over the items array, but does not actually generate additional tags in the DOM. This template contains a div element that displays each item.

ng-content:
ng-content is a directive used to embed externally passed content into a component. It is used as a slot in the component's template, allowing content to be injected inside the component when it is used.

Example:

<app-modal>
  <div class="modal-header">Header</div>
  <div class="modal-body">Content</div>
  <div class="modal-footer">Footer</div>
</app-modal>

In the above example, ng-content can be used inside the template of the app-modal component to embed the incoming content (header, body, footer) into the appropriate location.

To summarize the differences:

ng-template is used to define templates, usually used with structural directives.
ng-content is used to embed external content into slots inside the component.
Note that these concepts may change as Angular versions are updated, so when reviewing documentation or learning resources, please refer to the content that applies to the version of Angular you are using.

Guess you like

Origin blog.csdn.net/weixin_43160662/article/details/132439124