[Angular 2] Property Binding

本文深入解析Angular中的属性绑定与类绑定的使用场景与区别,通过实例展示了如何在DOM元素上应用属性与类,并强调了正确使用语法的重要性。

Property Binding is bind property NOT attribute!

 

import {Component, Input, Output, EventEmitter} from 'angular2/core';

@Component({
    selector: 'hero-item',
    styles: [
        '.active {color: red}'
    ],
    template: `
       <li [class.active]="isSelected"
        [attr.aria-label]="hero.name"
        (click)="selectHero(hero)">
            {{hero.name}}
       </li>
    `
})
// <li [ngClass]="{active: isSelected}"></li>

export class HeroItem{
    label="This is a super hero";
    isSelected = false;
    @Input() hero ;
    @Output() changed = new EventEmitter();
    constructor(){

    }

    selectHero(hero){
        this.changed.emit(hero);
        this.isSelected = true;
    }
}

 

So 'class' is attribute on DOM, but 'class.active' is an property.

'aria-label' is attribute, so need to write like 'attr.aria-label'.

 

If you don't like use 'class.active', you can use 'ngClass' as shown in commnets

转载于:https://www.cnblogs.com/Answer1215/p/5357667.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值