ng2 内置指令

ng2 内置指令

ng2 内置指令_第1张图片

1.NgClass -- Adds and removes CSS classes on an HTML element.
How To Use

...

...

...

...

...

Selectors

[ngClass]

Description

The CSS classes are updated as follows, depending on the type of the expression evaluation:

  • string the CSS classes listed in the string (space delimited) are added,
  • Array the CSS classes declared as Array elements are added,
  • Object keys are CSS classes that get added when the expression given in the value evaluates to a truthy value, otherwise they are removed.

2.ng-for TYPE-ALIAS of ng-for-of

How To Use

  • ...
  • ...
  • Selectors

    [ngFor][ngForOf]

    例子:

    {{i}} -{{item}}- {{isFirst}}- {{isLast}}- {{isEven}}- {{isOdd}}


    {{i}} -{{item}}- {{isFirst}}- {{isLast}}- {{isEven}}- {{isOdd}}

    总结:

    • *ngFor 是 template="ngFor 的简化语法
    • 访问 index,first,last,even,odd 时需要使用as 语法,或者 ** let i = index **不是很方便
    • track by 一般不使用track by的情况下,每次刷新DOM,都会删除原有的元素重新生成DOM结构,而使用track by 后,则可以识别实例与渲染DOM节点间的关联,从而可以利用已有的DOM 元素,不需要整个删除重新渲染。提高了性能。
    • 为元素绑定属性 [title]="i",[attr.data-index]="i" https://angular.io/guide/template-syntax

    Usage 1: Track by property of object

    *ngFor="let post of posts;trackBy:post?.id"
    

    is what same as angular's 1

    ng-repeat="post in posts track by post.id"
    

    Usage 2: Track using your own Function

    *ngFor="let post of posts;trackBy:identify"
    
    export class HomeworkAddStudentsPage {
        posts:Array<{id:number,data:string}>;   
    
        constructor() {
            this.posts = [  {id:1,data:'post with id 1'},
                            {id:2,data:'post with id 2'} ];
        }
    
        identify(index,item){
          //do what ever logic you need to come up with the unique identifier of your item in loop, I will just return the object id.
          return post.id 
         }
    

    }

    is what same as angular's 1

  • app.controller(function($scope){ $scope.identify = function(index, item) {return item.id}; });

    3.NgIf

    ng2 内置指令_第2张图片

    like condition? true-code : false-code

    4.NgStyle --- Update an HTML element styles.

    How To Use

    ...
    
    ...
    
    ...
    

    例1.

    style using ngStyle

    例2.

    style using ngStyle

    注意:'font-size.px': size 的写法,如果 'font-size': size 则不起作用。
    c -- Adds / removes DOM sub-trees when the nest match expressions matches the switch expression.

    How To Use

    
      ...
      ...
      ...
      
        
        
        
      
      ...
    
    

    例子:

    
    
    
    
    You selected : {{value}}

    1. Template - {{value}}
    2. Template - {{value}}
    3. Template - {{value}}
    Default Template

    6.NgPlural -- Adds / removes DOM sub-trees based on a numeric value. Tailored for pluralization.

    ng2 内置指令_第3张图片

    你可能感兴趣的:(ng2 内置指令)