來自官網:
這篇《英雄指南》涵蓋`了 Angular 的核心原理。這次建構的應用會涉及很多特性:獲得并顯示英雄清單,編輯所選英雄的詳情,并在英雄資料的多個視圖之間建立導航。這些特性,在成熟的、資料驅動的應用中經常見到。
完成本教程後,我們将學習足夠的 Angular 核心技術,并确信 Angular 确實能做到我們需要它做的。 我們将涵蓋大量入門級知識,同時我們也會看到大量連結,指向更深入的章節。
一 :為本地開發搭建環境
a.檢查@angular/cli版本.
在指令行輸入 ng -v -----版本号必須大于1.0.0-beta.24
b.建立工程
c.運作項目
指令行進入你的項目根目錄
執行 cnpm start
d.布局會引用Bootstrap布局(引入bootstrap插件)
隻使用它的css和一些圖示樣式---->隻需引入css檔案和fonts檔案
1.在src/assets檔案下建立bootstrap檔案夾
目錄結構:
-assets
-bootstrap
-css
-bootstrap.min.css
-fonts
2.在.app/app.component.html
<span class="glyphicon glyphicon-plus"></span>
3.浏覽器頁面呈現出圖示。引入bootstrap成功。
二:顯示此英雄
.app/app.compoent.ts
export class AppComponent {
title = 'Tour of Heroes';
hero = 'Windstorm';}
./app/app.component.html
<h1>`title`</h1><h2>`hero` details!</h2>`
儲存後,浏覽器應自動重新整理,顯示标題和英雄。
這裡的雙大括号是Angular中的插值表達式綁定文法。它們表示元件的<code>title</code>和<code>hero</code>屬性的值會作為字元串插入到HTML标簽中間。
三:General對象
建立一bean檔案夾(用于存放資料模型)
./src/bean/General.ts
建立General.ts
export class General{
constructor(
public id:number,
public name:String,
public source:String
){}
}
在.app/app.component.ts
引入
import {General} from "../bean/General";
general: General= {
id: 1,
name: '趙雲'};
.app/app.component.html
<h1>`title`</h1><h2>`general`.`name` details!</h2>
四;編輯英雄名字
使用者應該能在一個<code><input></code>輸入框中編輯英雄的名字。 當使用者輸入時,這個輸入框應該能同時顯示和修改英雄的<code>name</code>屬性。
也就是說,我們要在表單元素<code><input></code>群組件的<code>hero.name</code>屬性之間建立雙向綁定。
雙向綁定
<code>[(ngModel)]</code>是一個Angular文法,用與把<code>hero.name</code>綁定到輸入框中。 它的資料流是雙向的:從屬性到輸入框,并且從輸入框回到屬性。
注意:
.app/app.module.ts
引入
//雙向資料綁定依賴的子產品
import { FormsModule } from '@angular/forms';
imports: [
BrowserModule,
FormsModule
]
.app/app.component.html重構
<div>
<label>name: </label>
<input [(ngModel)]="general.name" placeholder="name"></div>
五:顯示我們的英雄
建立data檔案夾(用于存放資料)
./src/data/mock-general.ts
建立mock-general.ts
import {General} from '../bean/General';
export const Generals:General[]=[
new General(11,"孫武",'春秋'),
new General(12,"白起",'秦'),
new General(13,"霍去病",'西漢'),
new General(14,"馬援",'東漢'),
new General(15,"謝玄",'兩晉'),
new General(16,"張須陀",'隋'),
new General(17,"李靖",'唐'),
new General(18,"薛仁貴",'唐'),
new General(19,"嶽飛 ",'宋'),
new General(20,"戚繼光",'明'),
];
<code>HEROES</code>是一個由<code>Hero</code>類的執行個體構成的數組,我們在第一部分定義過它。 我們當然希望從一個 Web 服務中擷取這個英雄清單,但别急,我們得把步子邁得小一點,先用一組模拟出來的英雄。
./app/app.component.ts
1.導入import {Generals} from "../data/mock-general";
import { OnInit} from '@angular/core';
微調AppComponent
export class AppComponent implements OnInit {
title = 'MY General';
// generals:General[]=Generals;
generals:General[];
ngOnInit(){
this.generals=Generals;
}
*ngFor 官網https://angular.cn/guide/displaying-data#ngFor
重構./app/app.component.html
<div class="container">
<div class="row">
<h1>`title`</h1>
</div>
<div>
<ul >
<li *ngFor="let item of generals"><span>`item`.`id` </span> `item`.`name` `item`.`source`</li>
</ul>
當浏覽器重新整理時,我們就看到了英雄清單
本文轉自 沉迷學習中 51CTO部落格,原文連結:http://blog.51cto.com/12907581/1965007,如需轉載請自行聯系原作者