The ngFor directive is often used in projects, but it was only used before, and how it was implemented is unknown. I finally have time to “study” how it works these days, and write a simple ngFor directive: repeat

TemplateRef and ViewContainerRef have to be mentioned

  • TemplateRef can be understood as a DOM rendering template. Instructions create DOM elements from TemplateRef templates
  • ViewContainerRef can be understood as a container for TemplateRef, and when createEmbeddedView is called on ViewContainerRef, Dom elements are created by passing in TemplateRef and context. The Angular microsyntax is shown below.

Micro grammar
TemplateRef

Code examples:

import { Directive, Input, TemplateRef, ViewContainerRef } from "@angular/core";

@Directive({
  selector: "[appRepeat]"
})
export class RepeatDirective {
  constructor(private tpl: TemplateRef<any>, private vc: ViewContainerRef) {}

  @Input(a)set appRepeatIn(val: Array<any>) {
    val.forEach((item, index) = > {
      this.vc.createEmbeddedView(this.tpl, {
        $implicit: item,
        index: index,
        even: index % 2= = =0,
        odd: index % 2= = =1}); }); }}Copy the code
<ul>
  <li
    *appRepeat=" let item; in: items; let index = index; let even = even; let odd = odd; let defualt "
  >
    <ul class="{{ even ? 'even' : 'odd' }}">
      <li>index: {{ index }}</li>
      <li>item: {{ item }}</li>
      <li>default: {{ defualt }}</li>
      <li>even: {{ even }}</li>
      <li>odd: {{ odd }}</li>
    </ul>
  </li>
</ul>
Copy the code

You can see from the above code:

  • Let declaration variables (index,even,odd) can be assigned using the createEmbeddedView method to the property value of the context (index,even,odd). The value is assigned using the context’s attribute value ($implicit).
  • The Input attribute name of the Directive is in the format of “[selector]key”, following the CamelCase naming rules, such as the above example:
selector: "appRepeat"
key: "in"
Copy the code

The name is “appRepeatIn”.

  • A Directive creates a page view using incoming data

Summary: See how to create a simple structural directive in Angular, the micro syntax for directive expansion (expansion form, incoming data, assignment), and create DOM elements using createEmbeddedView and TemplateRef. If in doubt, check out the source code or leave a comment below