自学ng2 -绑定语法

单向 --从数据到视图 

  <img src="{{ expression }}" />,[ src ]="expression",bind-src="expression"

单向 --从视图到数据

  ( target )="statement",on-target="statement"

双向 --

  [( target )]="expression",bindon-target="expression"

attribute和property

  (attribute 是由 HTML 定义。property 是由 DOM 定义。attribute值不可变,property值可变)

  (HTML attribute value指定了初始值;DOM value property 是当前值。)

  (模板绑定是通过 property 和事件来工作的,而不是 attribute。)

绑定目标 --(元素 | 组件 | 指令的)property、event,attribute 名

各种绑定类型 --

  <img [src]="heroImageUrl">

  <button [disabled]="isUnchanged">Cancel is disabled</button>

  <div [ngClass]="classes">[ngClass] binding to the classes property</div>

  <app-hero-detail [hero]="currentHero"></app-hero-detail> (父子组件通讯重要途径)

  子:

    --deleteRequest = new EventEmitter<Hero>();

    --delete(){

      this.deleteRequest.emit(this.hero);

     }

  父:

    --<parent (deleteRequest)="deleteHero($event)" [hero]="currentHero"></parent>

双向绑定分解:

      <app [size]="fontSizePx"  (sizeChange)="fontSizePx=$event"></app>

      -- 原生html不支持x、xchange模式,可用NgModel指令来绑定    

        NgClass - 添加或移除一组CSS类

        NgStyle - 添加或移除一组CSS样式

        NgModel - 双向绑定到HTML表单元素

内置结构型指令

  *ngIf - 根据条件把一个元素添加到DOM中或从DOM移除

  *ngSwitch - 一组指令,用于切换一组视图

    <div [ngSwitch]="currentHero.emotion">

      <app-happy *ngSwitchCase="'happy'" [hero]="currentHero"></app-happy>

      <app-sad *ngSwitchCase="'sad'" [hero]="currentHero"></app-sad>

      <app-confused *ngSwitchCase="'confused'" [hero]="currentHero"></app-confused>

      <app-unknown *ngSwitchDefault [hero]="currentHero"></app-unknown>

    </div>

  *ngFor - 对列表中的每个条目重复套用同一个模板 (let a of b; let i=index; trackBy:   

      trackByHeroes)

    -- trackByHeroes(index: number, hero: Hero): number{ return hero.id }

    -- trackBy 避免对未改变Dom重复操作

模板引用变量

  -- 类似vue2的 $ref

  <input #phone placeholder="phone number">

  <button (click)="callPhone(phone.value)">Call</button>

输入输出属性(@Input、@Output)

  所有组件皆为指令

  绑定的目标是在=左侧的部分, 则是在=右侧的部分。

  目标属性必须被显式的标记为输入或输出。

  <hero-detail [hero]="currentHero" (deleteRequest)="deleteHero($event)">

       输入属性                           输出属性

  @Input() hero: Hero;

  @Output() deleteRequest = new EventEmitter<Hero>();

  @Component({ inputs: ['hero'], outputs: ['deleteRequest'], })

  @Directive({ outputs: ['clicks:myClick'] // propertyName:alias })

管道操作符

  <div>{{currentHero | json}}</div>  返回 json 数据

安全导航操作符和非空断言符

  {{myHero?.name}}

原文地址:https://www.cnblogs.com/SharkChilli/p/7978921.html