angular2學(xué)習(xí)筆記

demo設(shè)計(jì)原則:

  • 用vscode編輯器。
  • 構(gòu)建原型圖原型,想好邏輯。
  • 圍繞所學(xué)的內(nèi)容。
  • ts文件和class的命名規(guī)則

angular整體認(rèn)識(shí)

  • 模塊(module)
  • 組件(component)
  • 模板(template)
  • 元數(shù)據(jù)(metadata)
  • 數(shù)據(jù)綁定(data binding)
  • 指令(directive)
  • 服務(wù)(service)
  • 依賴注入(dependency injection)

下面根據(jù)官網(wǎng)Demo介紹知識(shí)點(diǎn)

編輯器

  • main.ts
platformBrowserDynamic().bootstrapModule(Module);
platformBrowserDynamic在@node_module/angular/platform-browser-dynamic中
應(yīng)用啟動(dòng)
  • module.ts

@NgModule 聲明根模塊,其中屬性有:

  1. declarations 聲明視圖類
  2. imports 導(dǎo)入全局組件模塊
  3. providers 創(chuàng)建服務(wù)到全局服務(wù)列表中,可用于任何部分
  4. bootstrap 指定主視圖,是其他視圖的宿主,只能根模塊設(shè)置
  • components.ts

    @Component用來(lái)把緊隨其后的類標(biāo)記標(biāo)記成組件類,其中配置項(xiàng)有:

    1. moduleId 為templateUrl提供根地址
    2. selector 組件標(biāo)簽名
    3. templateUrl 為模板提供相對(duì)地址
    4. template 頁(yè)面模板
    5. providers 組件所需服務(wù)(依賴注入,提供數(shù)據(jù))
  • 其他

  1. ``實(shí)現(xiàn)多行模板,方便編寫
  2. {{hero.name}} 單向數(shù)據(jù)綁定的“插值表達(dá)式”
  3. [(ngModel)]="hero.name"所需FormsModule模塊,實(shí)現(xiàn)雙向綁定
  4. *ngFor

主從結(jié)構(gòu)

該部分內(nèi)容是構(gòu)建數(shù)據(jù)數(shù)組,展示列表。其中知識(shí)點(diǎn):

  1. *ngIf 是否展示數(shù)據(jù)
  2. (click)="onSelect(hero)" cell點(diǎn)擊
  3. [class.selected]="hero === selectedHero" 屬性綁定

多組件

把具有單一職責(zé)的組件剝離出來(lái),達(dá)到可復(fù)用原則,其中知識(shí)點(diǎn):

  1. @Input()裝飾器
  2. 在app.module里聲明新增模塊,供其他模塊引用
  3. 在@Component里的selector定義標(biāo)簽名
  4. 單一職責(zé)原則

服務(wù)(數(shù)據(jù)服務(wù))

  1. 基于承諾(Promise)的數(shù)據(jù)服務(wù)
  2. mock模擬數(shù)據(jù),不要和UI耦合
  3. @Injectable()數(shù)據(jù)注入
  4. constructor初始化class
  5. OnInit周期

路由

路由器是一個(gè)可選的外部Angular NgModule,其包含多條指令(RouterOutlet、RouterLink、RouterLinkActive),在@angular/router中,名叫RouterModule。

  1. index.html添加<base href="/">
  2. 配置路由
import { RouterModule } from '@angular/router';
NgModule({
   imports: [
       BrowserModule, 
       FormsModule,
       RouterModule.forRoot([
           {
               path: 'heros',
               component: HerosComponent
           }
       ])
   ]
   .
   .
   .
path: 路由器會(huì)用它來(lái)匹配瀏覽器地址欄中的地址,如heroes。
component: 導(dǎo)航到此路由時(shí),路由器需要?jiǎng)?chuàng)建的組件(HeroesComponent)。
  1. 添加路由鏈接
template:`
   <h1>{{title}}</h1>
   <a routerLink="/heros">Heros</a>
   <router-outlet></router-outlet>
   `
  1. 首頁(yè)重定向
{
   path: '',
   redirectTo: '/dashboard',
   pathMatch: 'full'
}
  1. 共享HeroService(單例)
app.module.ts
@NgModule({
   providers: [HeroService]
})
  1. 配置帶參數(shù)路由
{
   path: 'detail/:id',
   component: HeroDetailComponent
}
  1. 跳轉(zhuǎn)路由另一種方式
this.router.navigate(['/detail', this.selectedHero.id]);
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容