zoukankan      html  css  js  c++  java
  • [Angular Directive] Write a Structural Directive in Angular 2

    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:

  • 相关阅读:
    矩阵乘法优化求斐波那契
    高斯消元
    NOIP201305转圈游戏
    双六问题
    线段上格点的个数
    如何写出优雅的Python代码?
    sock.listen()
    python socket编程
    sc,sockname = sock.accept()
    格式化字符
  • 原文地址:https://www.cnblogs.com/Answer1215/p/6212895.html
Copyright © 2011-2022 走看看