3、模版表达式

基本用法

import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
  template: `
    <h1>{{title}}</h1>
    <h2>My favorite hero is: {{myHero}}</h2>
    `,
  styles: [`h1 { color: red }`]
})
export class AppComponent {
  title = 'Tour of Heroes';
  myHero = 'Windstorm';
}

 

绑定方法

模版中除了绑定变量,还能绑定方法

import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
  template: `
      <div>Value: {{ getVal() }}/div>
  `,
})
export class AppComponent {
  getVal(): number {
    return 33;
  }
}

 

 

模板表达式

模版中还可以写些简单的逻辑,比如判断或运算

import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
  template: `
      <p>The sum of 1 + 1 is {{1 + 1}}.</p>
      <p>price的7折 {{price * 0.7}}.</p>
      <p>与方法结合 {{price * 0.7 + getVal()}}.</p>
  `,
})
export class AppComponent {
  price = 30
  getVal(): number {
    return 33;
  }
}

 

 

当使用模板表达式时,请遵循下列指南:

  • 非常简单
  • 执行迅速
  • 没有可见的副作用(即模版中的逻辑不能改变组件的变量)
posted @ 2020-10-11 14:21  jahoon  阅读(201)  评论(0)    收藏  举报