[入门级]angular4学习笔记02

数据绑定

往AppComponent.ts中添加两个属性:title属性用来显示应用名称,hero属性用来显示英雄名称

export class AppComponent{
  title = 'my first angular project';
  hero = 'yolanda';
}

更新@Component装饰器中指定的模版,为这些新属性建立数据绑定

template:'

{{title}}

{{hero}} details!

'

双括号是angular差值表达式绑定语法,它表示组件的属性title和hero的值会作为字符串插入到html标签中

hero对象

把hero从一个字符串字面量变成一个类,
创建一个Hero类,它具有id和name属性,下面是app.component.ts

import {Component} from @angular/core;
export class Hero{
  id : Number;
  name : String;
}
@Component({
  selector:'app-root',
  template:'.

{{title}}

{{hero}} details!

', styleUrls:'./app.component.css' }) export class appComponent{ title = 'Tours of heros'; hero : Hero = { id: 1, name : 'yolanda' } }

我们把hero从字符串变成了对象,也得更新模版中的绑定表达式,来引用hero中的name属性
下面是app.component.html

template:'.

{{title}}

{{hero.name}} details!

'

多行模版显示

反括号

template:`

title:{{title}}

hero:{{hero.name}}

`

双向数据绑定

重构app.component.ts的模版

{{title}}!

{{hero.name}} detail!

ngModel是一个有效的指令,它默认情况下是不可用的,它属于一个可选模块FormsModel
需要在app.module.ts中import

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms'; 添加这一行

import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule 在这里引入
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

总结

  • {{}}花括号插值表达式(单向数据绑定的一种形式)
  • 使用ES2015模版字符串(反引号)写了一个多行模版
  • 为了同时显示和修改英雄名字,使用了内置指令ngModel,往input元素上添加了双向设计绑定
  • ngModel指令将修改传播到每一个hero.name其他绑定
[入门级]angular4学习笔记02_第1张图片
公众号:前端咖秀

你可能感兴趣的:([入门级]angular4学习笔记02)