IDE平台为WebStorm2017.2
构建项目
- 利用脚手架,angular-cli构建项目 指令为ng new project
实例如下:
创建项目
#ng new Conquest001
启动项目
#cd Conquest
#npm start
ps:浏览器输入:127.0.0.1:4200
如果利用指令:ng serve --open 在项目目录下启动项目浏览器将自动打开网页
项目文件详解
仅编辑app.component.ts和app.module.ts
app.component.ts
导入核心库
import { Component } from '@angular/core';
模板样式:
@Component({
selector: 'app-root',
template: `<h1>{{title}}</h1>
<br>
<h2> -------{{from}}</h2>
<ul>
<li>
<div><label>ID:</label>{{hero.id}} <label> name:</label>{{hero.name}}</div>
</li>
</ul>
<div>
<label>name: </label>
<input [(ngModel)]="hero.name" placeholder="Change Name">
<label>ID: </label>
<input [(ngModel)]="hero.id" placeholder="Change ID">
</div>
` ,
styleUrls: ['./app.component.css']
})
双向绑定:此处两种双向绑定方式一样,只是前一个input中的写法更简洁,后者更易理解;用户应该能在一个输入框中编辑英雄的名字和ID。 当用户输入时,这个输入框应该能同时显示和修改英雄的name,ID属性。虽然NgModel是一个有效的Angular指令,但它默认情况下却是不可用的。 它属于一个可选模块FormsModule。 我们必须选择使用那个模块。
<div>
<label>name: </label>
<input [(ngModel)]="hero.name" >
<label>ID: </label>
<input [ngModel]="hero.id" (ngModelChange)="hero.id=$event">
</div>
样式路径:
styleUrls: ['./app.component.css']
字段初始化:字段之间分号结束,字段内容元素之间逗号结束
export class AppComponent {
title = 'My conquest is the sea of stars.';
from = 'Reinhard von Lohengramm';
hero: HeroProperty = {
id: 9527,
name: 'Lee',
};
}
字段属性定义:
export class HeroProperty {
id: number;
name: string;
}
app组件ts项目总览:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: `<h1>{{title}}</h1>
<br>
<h2> -------{{from}}</h2>
<ul>
<li>
<div><label>ID:</label>{{hero.id}} <label> name:</label>{{hero.name}}</div>
</li>
</ul>
<div>
<label>name: </label>
<input [(ngModel)]="hero.name" placeholder="Change Name">
<label>ID: </label>
<input [(ngModel)]="hero.id" placeholder="Change ID">
</div>
`
,
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'My conquest is the sea of stars.';
from = 'Reinhard von Lohengramm';
hero: HeroProperty = {
id: 9527,
name: 'Lee',
};
}
export class HeroProperty{
id: number;
name: string;
}
PS:由于WebStorm 里自带了TypeScript编译器,能将其在编辑ts文件同时转化成js文件
app.module.ts
模块导入管理组件:上面双向绑定所需的导入 FormsModule就是要在app.module.ts文件里从@angular/forms库中导入符号FormsModule。 然后把FormsModule添加到@NgModule元数据的imports数组中,它是当前应用正在使用的外部模块列表。
//
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { FormsModule } from '@angular/forms';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
FormsModule,
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }