Home > Web Front-end > JS Tutorial > body text

Let's talk about the understanding and usage of NgTemplateOutlet directive in Angular

青灯夜游
Release: 2021-11-05 10:12:48
forward
2632 people have browsed it

This article will take you through the NgTemplateOutlet directive in Angular and introduce the understanding and application of the structural directive NgTemplateOutlet. I hope it will be helpful to you!

Let's talk about the understanding and usage of NgTemplateOutlet directive in Angular

I recently saw this NgTemplateOutlet structural directive when I was watching a training project, but I have never been exposed to it before and I don’t know about it. How to use it? Then, I went to the official website to search for this API (Official website link click here).

But I don’t understand the API description. I don’t know what the so-called context object is, and I don’t know what the let variable is. Then after a whole day of flipping through documents and taking notes, I finally figured out what this is. Friends who haven’t figured it out can refer to my last article: [Angular Learning] About template input variables (let-variable) understanding

This article just talks about the usage and usage scenarios of NgTemplateOutlet. [Related tutorial recommendations: "angular tutorial"]

How to use

According to the official website, this API is like this:

Insert an inline view based on a prepared TemplateRef.

I will translate it: Make the host element of NgTemplateOutlet become an inline view - this inline view is based on a pre-defined The templateRef template reference is generated. No matter what element the host element is, it will not be rendered.

Let’s change the example on the official website (because I can’t understand the official website):

@Component({
  selector: 'ng-template-outlet-example',
  template: `
    <ng-container *ngTemplateOutlet="one"></ng-container>
    <hr>
    <ng-container *ngTemplateOutlet="two; context: myContext"></ng-container>
    <hr>
    <ng-container *ngTemplateOutlet="three; context: myContext"></ng-container>
    <hr>

    <ng-template #one><span>Hello</span></ng-template>
    <ng-template #two let-name><span>Hello {{name}}!</span></ng-template>
    <ng-template #three let-person="lastName">My name is <span>LeBron {{person}}!</span></ng-template>
`
})
export class NgTemplateOutletExample {
  myContext = {$implicit: &#39;World&#39;, lastName: &#39;James&#39;};
}
Copy after login

A host element can use the ngTemplateOutlet structural directive to make itself Become an inline view generated by any <ng-template> template. And you can set context object to it. Then we can use the let-variable template input variable in this template to get the value in the context object. This template is more flexible.

Application Scenario

Similar to ng-zorroThe paging component of this frameworkPaginationOfficial website link). If we are not satisfied with the style or structure of the default previous page and next page and want to adjust it ourselves, we can provide an input attribute (attribute defined by @Input) to receive a template and provide it with the necessary Properties or methods. In this case, we can reuse components without modifying the component source code.

Demo

We first define a sub-component HeroDisplayCard, the character’s display interface

@Component({
  selector:&#39;app-hero-display-card&#39;,
  template:`
    <h2 [style]="{textAlign:&#39;center&#39;}">角色列表</h2>
    <ul class="hero-card-box">
      <li class="hero-card-item" *ngFor="let h of heroesList">
        <p [style]="{textAlign:&#39;center&#39;}">
          角色id:{{h.id}}--
          角色名字:{{h.name}}--
          角色属性:{{h.features}}
        </p>
      </li>
    </ul>
  `,
  styles:[
    `.hero-card-box{
      width: 600px;
      margin: 10px auto;
    }
    .hero-card-item{
      list-style: none;
    }
    `
  ]
})
export class HeroDisplayCard {
  public heroesList = [
    {id:&#39;013&#39;,name:&#39;钟离&#39;,features:&#39;rock&#39;},
    {id:&#39;061&#39;,name:&#39;烟绯&#39;,features:&#39;fire&#39;},
    {id:&#39;022&#39;,name:&#39;迪奥娜&#39;,features:&#39;ice&#39;},
    {id:&#39;004&#39;,name:&#39;诺艾尔&#39;,features:&#39;rock&#39;},
  ]
}
Copy after login

and then introduce this component into a In the parent component:

@Component({
  selector:&#39;app-templateoutlet-app-demo&#39;,
  template:`
    <app-hero-display-card></app-hero-display-card>
  `
})
export class TemplateOutletAppDemoComponent {}
Copy after login

Run the code, the effect is as shown:

Lets talk about the understanding and usage of NgTemplateOutlet directive in Angular

## I think the style of this

li is really ugly , and the order is not quite right. I want to put the character attributes before the character name. In this case, it will be very troublesome to simply change the style by inputting attributes. We may need to define a lot of variables for users to choose, which is not worth the gain. So why don't we directly provide a template to the user, we only need to provide the necessary data. The freedom of style and layout is left to the user.

So for the sub-component

HeroDisplayCard we can change it like this:

@Component({
  selector:&#39;app-hero-display-card&#39;,
  template:`
    <h2 [style]="{textAlign:&#39;center&#39;}">角色列表</h2>
    <ul class="hero-card-box">
      <ng-container *ngFor="let h of heroesList">
        <!-- 如果没有传入cardItemTemplate则显示默认 -->
        <li class="hero-card-item" *ngIf="!cardItemTemplate">
          <p [style]="{textAlign:&#39;center&#39;}">
            角色id:{{h.id}}--
            角色名字:{{h.name}}--
            角色属性:{{h.features}}
          </p>
        </li>
        <!-- 如果传入了自定义模板,则显示出来,鉴于angular的结构型指令不能在同一个宿主元素上的规定,于是这样写 -->
        <ng-container *ngIf="cardItemTemplate">
		  <!-- 将自定义模板的上下文对象设置为h -->
          <ng-container *ngTemplateOutlet="cardItemTemplate;context:h"></ng-container>
        </ng-container>
      </ng-container>
    </ul>
  `,
  styles:[ //省略 ]
})
export class HeroDisplayCard {
  @Input() cardItemTemplate:TemplateRef<any>;
  public heroesList = [ // 省略]
}
Copy after login

Then we pass the custom template into the parent component:

@Component({
  selector:&#39;app-templateoutlet-app-demo&#39;,
  template:`
    <app-hero-display-card [cardItemTemplate]="myCardTemplate"></app-hero-display-card>
	<!-- 将模板引用变量myCardTemplate传入子组件 -->
    <ng-template #myCardTemplate let-id="id" let-name="name" let-features="features">
      <li class="hero-card-custom-item">
        <p>角色id:<span>{{id}}</span></p>
        <p>角色属性:<span>{{features}}</span></p>
        <p>角色名字:<span>{{name}}</span></p>
      </li>
    </ng-template>
  `,
  styles:[
    //在这里写自定义模板的样式  
    `.hero-card-custom-item{
      width: 100%;
      height: 35px;
      border: 1px solid #999999;
      border-radius: 5px;
      display: flex;
      justify-content:space-around;
      align-items: center;
      margin: 10px 0;
    }
    .hero-card-custom-item p {
      width: 30%;
      margin: 0;
      font-size: 20px;
      color: #666666;
    }
    .hero-card-custom-item p span {
      color: red;
    }`
  ]
})
export class TemplateOutletAppDemoComponent {}
Copy after login
Then run it, the effect is as shown below (actually it is still very ugly):

Lets talk about the understanding and usage of NgTemplateOutlet directive in Angular

##Summary

Use

NgTemplateOutlet

This structural directive can enhance the encapsulation of our sub-components and avoid the need to define a large number of input attributes, causing the template of the parent component to look bloated. For more programming-related knowledge, please visit:

Introduction to Programming

! !

The above is the detailed content of Let's talk about the understanding and usage of NgTemplateOutlet directive in Angular. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:juejin.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template