4、属性绑定

绑定图片

import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
  template: `
    <img src="../assets/images/madao.jpg" alt="madao" />
    <img [src]="madaoSrc" alt="madao" />
    <img bind-src="madaoSrc" alt="madao" />
    `,
  styles: []
})
export class AppComponent {
  madaoSrc = '../assets/images/madao.jpg';
}

 

绑定普通属性

import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
  template: `
    <img [src]="user.pic" [alt]="user.name" />
    <table class="table-bordered">
      <tr>
        <th>name</th>
        <th>phone</th>
        <th>age</th>
      </tr>
      <tr>
        <td>张三</td>
        <td>13398490594</td>
        <td>33</td>
      </tr>
      <tr>
        <td [colSpan]="colSpan">李四</td>
        <td>15079049984</td>
        <td>22</td>
      </tr>
    </table>
    <button class="btn btn-primary" [disabled]="isDisabled">click</button>
    `,
  styles: []
})
export class AppComponent {
  madaoSrc = '../assets/images/madao.jpg';
  user = {
   name: 'madao',
   pic: this.madaoSrc
  };
  colSpan = 2;
  isDisabled = false;
}
 

绑定自定义属性

import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
  template: `
    <span [attr.data-title]="customTitle">一行文字</span>
    <span [attr.title]="customTitle">test title</span>
    <span [title]="customTitle">test title</span>
    `,
  styles: []
})
export class AppComponent {
  madaoSrc = '../assets/images/madao.jpg';
  customTitle = 'bbb';
}

 

使用插值表达式

插值也可以用于属性,但常规做法还是用中括号[],建议整个项目保持风格统一

import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
  template: `
    <img src="{{ user.pic }}" alt="{{ user.name }}" />
    `,
  styles: []
})
export class AppComponent {
  madaoSrc = '../assets/images/madao.jpg';
  user = {
    name: 'madao',
    pic: this.madaoSrc
  };
}

 

 
posted @ 2020-10-11 14:47  jahoon  阅读(122)  评论(0)    收藏  举报