美文网首页
angular4 学习第二天(内置指令)

angular4 学习第二天(内置指令)

作者: 虚蕪面孔 | 来源:发表于2017-12-08 15:10 被阅读10次

    一、angular 内置指令学习
    (一) 属性型指令
    属性型指令会监听和修改其它HTML元素或组件的行为、元素属性(Attribute)、DOM属性(Property)。 它们通常会作为HTML属性的名称而应用在元素上。
    1..NgClass 指令
    我们经常用动态添加或删除 CSS 类的方式来控制元素如何显示。 通过绑定到`[NgClass],可以同时添加或移除多个类。
    this.currentClasses = {
    'saveable': this.canSave,
    'modified': !this.isUnchanged,
    'special': this.isSpecial
    };
    <div [ngClass]="currentClasses">This div is initially saveable, unchanged, and special</div>

    2.NgStyle 指令
    我们可以根据组件的状态动态设置内联样式。NgStyle 绑定可以同时设置多个内联样式。
    this.currentStyles = {
    'font-style': this.canSave ? 'italic' : 'normal',
    'font-weight': !this.isUnchanged ? 'bold' : 'normal',
    'font-size': this.isSpecial ? '24px' : '12px'
    };
    [NgStyle]属性绑定到currentStyles`,以据此设置此元素的样式:

    <div [ngStyle]="currentStyles">
    This div is initially italic, normal weight, and extra large (24px).
    </div>
    3.NgModel 指令 使用[(ngModel)]双向绑定到表单元素
    例如 <input [(ngModel)]="currentHero.name">
    使用NgModel需要FormsModule
    import { [FormsModule]}from'@angular/forms';// <-
    @Ngmodule({
    imports:[
    FormsModule
    ]
    })
    (二)结构型指令
    结构型指令的职责是HTML布局。 它们塑造或重塑DOM的结构,这通常是通过添加、移除和操纵它们所附加到的宿主元素来实现的。
    1.NgIf
    <app-hero-detail ngIf="isActive"></app-hero-detail>
    当isActive 为false ngIf会从页面删除这个dom元素
    注:别忘了ngIf 前面的星号(
    )。
    2.NgSwith
    .NgSwith 指令类似于JavaScript的switch语句。 它可以从多个可能的元素中根据switch条件来显示某一个。
    NgSwith 实际上包括三个相互协作的指令:NgSwith NgSwithCase NgSwithDefault
    <div [ngSwitch]="currentHero.emotion">
    <app-happy-hero *ngSwitchCase="'happy'" [hero]="currentHero"></app-happy-hero>
    <app-sad-hero *ngSwitchCase="'sad'" [hero]="currentHero"></app-sad-hero>
    <app-confused-hero *ngSwitchCase="'confused'" [hero]="currentHero"></app-confused-hero>
    <app-unknown-hero ngSwitchDefault [hero]="currentHero"></app-unknown-hero>
    </div>
    3.NgForOf
    ngFor 是一个重复器指令 —— 自定义数据显示的一种方式。
    <div ngFor="let hero of heroes">{{hero.name}}</div>
    注:别忘了ngFor 前面的星号(
    )。
    带索引的
    ngFor
    *ngFor指令上下文中的index属性返回一个从零开始的索引,表示当前条目在迭代中的顺序。 我们可以通过模板输入变量捕获这个index值,并把它用在模板中。
    <div *ngFor="let hero of heroes; let i=index">{{i + 1}} - {{hero.name}}</div>

    相关文章

      网友评论

          本文标题:angular4 学习第二天(内置指令)

          本文链接:https://www.haomeiwen.com/subject/fzkeixtx.html