angular2学习笔记(1)

来源:互联网 发布:字符串的全排列 java 编辑:程序博客网 时间:2024/06/05 16:14

对象的使用:


可以看一下Angular2.0的官网给出的Demo https://angular.io


英雄联盟APP开发:


在Hello angular学习之后,在Hello angular 基础上学习如何开发难度大一点的应用。 拷贝上一节的Hello angular目录内容到新目录 angular-two。拷贝完成后 使用 cnpm start 命令运行一下 看是否可以正常运行。

D:\angular2\angular-two>npm start

在AppComponent中增加2个属性 title和hero 代码如下:

export class AppComponent {     public title = '英雄联盟';    public hero = '法外狂徒';}

修改一下组件中Template中的代码,看一下绑定的数据

template: '<h1>{{title}}</h1><h2>{{hero}} details!</h2>'

Hero 对象:


上面的hero只是一个字符串,如果hero需要更多的属性,我们把字符串更改为interface来定义,定义interface对象的代码写在最上面。例如:

interface Hero {  id: number;  name: string;}

当需要除简单类型之外的对象时,需要用到interface或者class,当一个类带有逻辑或者运行状态的时候需要定义为class,当只是检查类型匹配,interface足以,而且轻量级。
现在定义了一个Hero对象,替换一下原来的hero的内容,修改一下template的内容,

新的app.component.ts代码如下

import {Component} from 'angular2/core';interface Hero {  id: number;  name: string;}@Component({    selector: 'my-app',    template: '<h1>{{title}}</h1><h2>{{hero.name}}</h2><div><label>id: </label>{{hero.id}}</div><div><label>name: </label>{{hero.name}}</div>'})export class AppComponent {     public title = '英雄联盟';      public hero: Hero = {        id: 1,        name: '法外狂徒'    };}


如果是多行的template,需要使用` (顿号)包裹。例如:
@Component({    selector: 'my-app',    template: `    <h1>{{title}}</h1>    <h2>{{hero.name}}</h2>    <div><label>id: </label>{{hero.id}}</div>    <div><label>name: </label>{{hero.name}}</div>    `})

hero的name如果需要编辑 使用input进行替换,重构一下代码:
template:`  <h1>{{title}}</h1>  <h2>{{hero.name}} </h2>  <div><label>id: </label>{{hero.id}}</div>  <div>    <label>name: </label>    <div><input value="{{hero.name}}" placeholder="name"></div>  </div>  `

如果需要input里面的内容和h2的内容联动,当input里面的内容更改时,h2上的内容也跟着更改。需要使用angular的ngModel进行双向数据绑定。
<input [(ngModel)]="hero.name"  placeholder="name">

查看浏览器 发现 input里面输入什么, h2显示什么,这样就相互联动起来了。
下面是app.component.ts完整代码:
import {Component} from 'angular2/core';interface Hero {  id: number;  name: string;}@Component({    selector: 'app-root',    template: `    <h1>{{title}}</h1>    <h2>{{hero.name}} </h2>    <div><label>id: </label>{{hero.id}}</div>    <div>         <label>name: </label>         <div>               <input [(ngModel)]="hero.name"    placeholder="name">         </div>     </div>      `})export class AppComponent {     public title = '英雄联盟';      public hero: Hero = {        id: 1,        name: '法外狂徒'    };}



后续更新 敬请期待!


0 0