Home  >  Article  >  Web Front-end  >  Detailed explanation of template input variables (let-variables) in Angular

Detailed explanation of template input variables (let-variables) in Angular

青灯夜游
青灯夜游forward
2021-05-06 10:13:463634browse

This article will take you through the template input variables (let-variables) in Angular. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

Detailed explanation of template input variables (let-variables) in Angular

As a person like me, I don’t like to directly copy things from the official website when writing articles or sharing my experiences. It’s really meaningless. I still like to write articles in my vernacular. I spent a long time on the official website today about template input variables, and finally got a preliminary understanding of what it is.

So what exactly is a template input variable?

The reason why I want to study this thing is that when I used ng-zorro before, I used it Its paging component Pagination (Official website link). There is a customize the previous page and next page template function. The code is as follows:

@Component({
  selector: 'nz-demo-pagination-item-render',
  template: `
    <nz-pagination [nzPageIndex]="1" [nzTotal]="500" [nzItemRender]="renderItemTemplate"></nz-pagination>
    <ng-template #renderItemTemplate let-type let-page="page">
      <ng-container [ngSwitch]="type">
        <a *ngSwitchCase="&#39;page&#39;">{{ page }}</a>
        <a *ngSwitchCase="&#39;prev&#39;">Previous</a>
        <a *ngSwitchCase="&#39;next&#39;">Next</a>
        <a *ngSwitchCase="&#39;prev_5&#39;"><<</a>
        <a *ngSwitchCase="&#39;next_5&#39;">>></a>
      </ng-container>
    </ng-template>
  `
})
export class NzDemoPaginationItemRenderComponent {}

After reading this, I was very confused. What is this let? Why does let- have a value after being followed by a variable? Then I started looking for what this let is on the official website. Finally, I found the explanation about let in the Microgrammar section of Main Concepts-Instructions-Structural Instructions. Official website description: Microgrammar. [Related recommendation: "angular tutorial"]

There is also a brief explanation below:

Template input variable (Template input variable)

A template input variable is a variable whose value you can reference in a single instance of a template. There are several template input variables in this example: hero, i, and odd. They all use let as the leading keyword.

......

You declare a template

input in a template using the let keyword (such as let hero) variable. The scope of this variable is limited to the single instance of the template being repeated. In fact, you can use the same variable name in other structural directives.

......

The official website is still as non-verbal as ever. It introduces it to you in just a few sentences and doesn't tell you how to use it. It also doesn't tell you where the value of the variable declared by

let comes from. The more I read, the angrier I became. Well, if you don’t tell me about the official website, I’ll find it myself.

Let’s start with a rough conclusion:

The variable declared by let is the variable in the context object of this template template. Otherwise, why is it called template input variable? In the *ngFor Insider section, we learned the inside story. The structural directive actually wraps the host element in a , and then parse the expression in *ngFor on this template into each let template input variable and the value that needs to be passed in for this instruction. Since the code in the template will not be directly rendered into a view, there must be some way to turn the template into a view. Our structural directives do just that, turn our templates into views. The official sample code of

*ngFor is as follows:

//解析前的模板
<div *ngFor="let hero of heroes; let i=index; let odd=odd; trackBy: trackById" [class.odd]="odd">
  ({{i}}) {{hero.name}}
</div>
//angular解析后的模板
<ng-template ngFor let-hero [ngForOf]="heroes" let-i="index" let-odd="odd" [ngForTrackBy]="trackById">
  <div [class.odd]="odd">({{i}}) {{hero.name}}</div>
</ng-template>

    As a reminder, the so-called
  • host element is the one where the instruction is located Element, like in the above example, div is the host element of the *ngFor directive.
  • trackByThis is similar to the key in vue and react. You can give the template an identifier to reduce the performance overhead when re-rendering it.
Then let’s look at what the official website says:

  • let-i and let-odd variables are Defined by let i=index and let odd=odd. Angular sets them to the current values ​​of the index and odd properties in the context object.
  • The context attribute of
  • let-hero is not specified here. Its origin is implicit. Angular sets let-hero to the value of the $implicit property in this context, which is initialized by NgFor with the hero in the current iteration.
After reading this description, we can know:

angular sets the context object for this template. But we can't see this process because it is implemented inside the source code of ngFor. And this context object has index and odd attributes, and contains an $implicit (implicit: implicit; not directly stated) properties. Then we infer that this context object has at least the following attributes:

{
    $implicit:null,
    index:null,
    odd:null,
}

那么我们声明let变量的本质其实就是声明一个变量获取上下文对象中的同名属性的值let-hero不进行任何赋值的话,hero默认等于$implicit的值。无论是有多少个let-alet-blet-c还是let-me。声明的这个变量的值都等于$implicit的值。而我们进行赋值过的,比如let-i = "index"i的值就等于这个上下文对象中的index属性对应的值。

上下文对象是如何设置的

当我们知道这个上下文对象是什么了,就该想这个上下文对象是怎么设置的了

结构性指令这一节当中,我们跟着官方示例做了一遍这个自定义结构性指令(如果还没有做的话,建议先跟着做一遍)。在UnlessDirective这个指令中,其构造器constructor声明了两个可注入的变量,分别是TemplateRefViewContainerRef。官网给的解释我觉得太过晦涩难懂,我这里给出一下我自己的理解:TemplateRef代表的是宿主元素被包裹之后形成的模板的引用。而ViewContainerRef代表的是一个视图容器的引用。那么问题来了,这个视图容器在哪儿呢?我们在constructor构造器中打印一下ViewContainerRef。打印结果如图:

Detailed explanation of template input variables (let-variables) in Angular

然后我们点进去这个comment元素。发现其就是一个注释元素。如图所示:

Detailed explanation of template input variables (let-variables) in Angular

其实我也不是很确定这个视图容器到底是不是这个注释元素。但是毋庸置疑的是,视图容器和宿主元素是兄弟关系,紧挨着宿主元素。我们可以使用ViewContainerRef中的createEmbeddedView() 方法(Embedded:嵌入式,内嵌式),将templateRef模板引用传入进去,创建出来一个真实的视图。由于这个视图是被插入到视图容器ViewContainerRef中了,所以又叫内嵌视图。那么这又和我们的上下文对象有什么关系呢?其实createEmbeddedView这个方法不止一个参数,其第二个参数就是给我们的模板设置上下文对象的。API的详情介绍请看createEmbeddedView这个API的详情

Detailed explanation of template input variables (let-variables) in Angular

就这样。我们就可以将上下文对象塞入模板中了,这样的话我们也可以直接使用let声明变量的方法来使用这个上下文对象了。

自定义一个简单的类*ngFor指令——appRepeat

那么我们知道是如何设置的了,那么我们就来验证一下是否是对的。接下来,我们仿照ngfor的功能,自己写一个简单的渲染指令。

首先我们定义一个指令:RepeatDirective。代码如下:

@Directive({
  selector: &#39;[appRepeat]&#39;,
})
export class RepeatDirective {
  constructor(
    private templateRef: TemplateRef<any>,
    private viewContainer: ViewContainerRef,
  ) { }

  @Input() set appRepeatOf(heroesList: string[]) {
    heroesList.forEach((item, index, arr) => {
      this.viewContainer.createEmbeddedView(this.templateRef, {
        //当前条目的默认值
        $implicit: item,
        //可迭代对象的总数
        count: arr.length,
        //当前条目的索引值
        index: index,
        //如果当前条目在可迭代对象中的索引号为偶数则为 true。
        even: index % 2 === 0,
        //如果当前条目在可迭代对象中的索引号为奇数则为 true。
        odd: index % 2 === 1,
      });
    });
  }
}

然后我们将其导入NgModule中,这个过程就省略不写了。然后我们在组件中使用一下这个指令:

@Component({
  selector: &#39;app-structural-likeNgFor-demo&#39;,
  template: `
    <h2>原神1.5版本卡池角色</h2>
    <h4>自定义ngFor(appRepeat)</h4>
    <ul>
      <li *appRepeat="let h of heroesList;let i = index;let even = even">
        索引:{{i}} -- {{h}} -- 索引值是否是偶数:{{even.toString()}}
      </li>
    </ul>
    <h4>真正的ngFor</h4>
    <ul>
      <li *ngFor="let h of heroesList;let i = index;let even = even">
        索引:{{i}} -- {{h}} -- 索引值是否是偶数:{{even.toString()}}
      </li>
    </ul>
  `,
})
export class StructuralLikeNgForDemoComponent {
  public heroesList: string[] = [&#39;钟离&#39;, &#39;烟绯&#39;, &#39;诺艾尔&#39;, &#39;迪奥娜&#39;];
}

在这里需要注意的是指令中的appRepeatOf不是乱写的。在微语法的解析过程中let h of heroesList中的of首先首字母会变成大写的,变成Of。然后在给它加上这个指令的前缀,也就是appRepeat。组合起来就是appRepeatOf了。由它来接收一个可迭代的对象。

最后显示的效果图:

Detailed explanation of template input variables (let-variables) in Angular

运行结果的话和*ngFor没有区别。但是功能肯定是欠缺的,如果有能力的小伙伴可以去阅读*ngFor的源码:*ngFor的源码

Summary

Through this article, we know that let-variableThis template input variable is passed through the template Defined in the context object and get the value. Then if you want to set the context object, you need to set it through the second parameter of the createEmbeddedView method.

Conclusion

But I always feel that the understanding is not thorough enough. I always feel that the context object of setting the template may not be just createEmbeddedView This is a method, but I didn't find any other method. If you guys know of other methods, please leave a message and let me know.

References:

This article is inspired by: Angular implements a "repeat" directive

More programming related For knowledge, please visit: programming video! !

The above is the detailed content of Detailed explanation of template input variables (let-variables) in Angular. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:juejin.cn. If there is any infringement, please contact admin@php.cn delete