zl程序教程

您现在的位置是:首页 >  前端

当前栏目

[Angular Directive] Write a Structural Directive in Angular 2

Angular in Write directive
2023-09-14 09:00:52 时间

Structural directives enable you to use an element as a template for creating additional elements. Creating structural directives requires a knowledge of <template> elements, but they're easy and extremely powerful once you undrestand the concepts.

 

What is stuctural looks like: 

<h1 *structure>This is structure directive</h1>

<!-- Equals to --> 
<template structure>
    <h1>This is structure directive</h1>
</template>

So Structural Directive is just something shorthand for template.

 

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

@Directive({
  selector: '[structure]'
})
export class StructureDirective {

  @Input('structure') num;

  constructor(private template: TemplateRef<any>,
              private view: ViewContainerRef) {
  }

  ngAfterContentInit() {

    let num: number = Number(this.num);
    if (num > 0) {
      while (num --){
        this.view.createEmbeddedView(this.template);
      }
    }

  }
}

 

<h1 *structure="'4'">This is structure directive</h1>

 

So it will print out: