Angular2 模板语法精粹之浅出

    xiaoxiao2021-03-26  27

    承接上一篇文章,Angular2 模板语法精粹之深入,这篇文章主要介绍了 angular2 内置的一些常用模板语法,看完这篇的内容,可以很快的使用内置指令和语法,构建出常用的组件模板,完成工作中大部分的需求逻辑

    常用内置指令


    NgClass

    private classes = { active: this.isActive, change: this.isChanged } // template <div [ngClass]="classes"></div>

    NgClass 接收一个对象,key 为 class 名字,value: boolean 如果为 true,则目标元素会添加这个 class ,为 false 目标元素会移除这个 class


    NgStyle

    private styles = { 'color': this.isRed? 'red': 'green', 'font-size': this.isTitle? '24px': '12px' } // template <div [ngStyle]="styles"></div>

    NgStyle 接收一个对象,key 为样式名称,value 为样式值


    NgIf

    结构指令

    <hero-detail *ngIf="isActive"></hero-detail>

    从 DOM 树中移除或添加元素,根据指令接收到的 boolean 值


    NgSwitch

    <span [ngSwitch]="toeChoice"> <span *ngSwitchCase="'Kevin'">Kevin</span> <span *ngSwitchCase="'Loch'">Loch</span> <span *ngSwitchDefault>other</span> </span>

    父指令绑定了开关的值,任何情况下,只有一个开关 case 会被显示出来


    NgFor

    <div *ngFor="let hero of heroes">{{hero.fullName}}</div>

    上下文中多了 hero,相当于在子作用域

    let hero of heroes 是 angular 自己解释的微语法

    <div *ngFor="let hero fo heroes; let i=index">{{i+1}}</div>

    最小更新代价,为了避免 heroes 数组中的微小改动,导致整个列表的重构与重绘,可以制定一个追踪函数,作为是否需要重构的标准

    trackByHeroes(index: number, hero: Hero) { return hero.id } <div *ngFor="let hero of heroes; trackBy: trackByHeroes">...</div>

    追踪函数中的 id 并不会影响该 id 下属性变化导致的重写,如果相同 id 下英雄的名字发生变化,DOM 同样会更新


    模版引用变量


    模版引用变量是模版中对 DOM 元素或指令的引用

    可以在同一元素、兄弟元素或任何子元素中使用模版引用变量

    <input #phone /> <button (click)="callPhone(phone.value)"></button> <input ref-phone /> <button (click)="callPhone(phone.value)"></button>

    上面是定义模版引用变量的两种形式,#phone 在这里都是原生的 HTMLInputElement


    NgForm

    <form (ngSubmit)="onSubmit(theForm)" #theForm="ngForm"> <button [disabled]="!theForm.form.valid">...</button> </form>

    这里的 theForm 是一个 NgForm 的实例,包装了原生的 HTMLFormElement,扩展了更多的功能


    输入与输出属性


    对于目标,分为输入与输出属性

    <hero-detail [hero]="currentHero" (deleteRequest)="deleteHero($event)"></hero-detail> @Input() hero: Hero; @Output() deleteRequest = new EventEmitter<Hero>();

    想了一个很好理解的比喻

    [hero] 是一吃货,他把 currentHero 吃到了指令内部

    (deleteRequest) 喝多了,他把 $event 吐给了 deleteHero() (作为参数),同时惹恼了 deleteHero(触发了事件)


    模版表达式操作符


    管道符

    <div>{{title | uppercase }}</div>

    管道操作符会把左侧表达式的结果传递给右侧的管道函数


    安全导航操作符(可选符)?.

    {{currentHero?.firstName}} // 放置currentHero null || undefined 报错

    完美的语法糖

    **

    前行的路上,感谢您的鼓励!!

    **

    转载请注明原文地址: https://ju.6miu.com/read-350118.html

    最新回复(0)