Angular項目結構分析
|---e2e //在e2e下是端到端(End-to-End)測試
|---node_modules //第三方模塊
|---src //編寫的項目文件都放在這個文件夾裏面
|---app //組件
|---app.component.html //根組件頁面
|---app.component.sass //根組件樣式
|---app.component.spec.ts //測試用例
|---app.component.ts //根組件
|---app.module.ts //根模塊
|---app-routing.module.ts //根路由
|---assets //靜態資源 圖片 第三方庫
|---.gitkeep
|---environments //開發模式和生產模式的配置文件,可以吧接口的更路徑寫在這裏面
|---environment.prod.ts
|---environment.ts
|---favicon.ico //小圖標 瀏覽器用的
|---index.html //啓動頁
|---main.ts //入口文件
|---polyfills.ts //兼容膩子腳本,可以配置兼容ie以及es6 es7
|---styles.sass //全局樣式
|---test.ts //測試用例
|---.editorconfig //editorconfig配置文件,規範開發用的
|---.gitignore //git忽略文件
|---package.json
|---package-lock.json
|---README.md
|---tsconfig.app.json //typescript配置文件
|---typescript.json //typescript配置文件
|---tslint.json //tslint語法校驗配置文件
文件內容介紹
app.module.ts
/*這個文件是Angular 根模塊,告訴Angular如何組裝應用*/
//BrowserModule,瀏覽器解析的模塊
import { BrowserModule } from '@angular/platform-browser';
//Angular核心模塊
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
/*@NgModule裝飾器, @NgModule接受一個元數據對象,告訴 Angular 如何編譯和啓動應用*/
@NgModule({
declarations: [ /*配置當前項目運行的的組件*/
AppComponent
],
imports: [ /*配置當前模塊運行依賴的其他模塊*/
BrowserModule,
AppRoutingModule
],
providers: [],/*配置項目所需要的服務*/
bootstrap: [AppComponent] /* 指定應用的主視圖(稱爲根組件) 通過引導根AppModule來啓動應用 ,這裏一般寫的是根組件*/
})
//根模塊不需要導出任何東西, 因爲其它組件不需要導入根模塊
export class AppModule { }
app.component.ts
//引入核心模塊裏面的Component
import { Component } from '@angular/core';
@Component({
selector: 'app-root', //使用這個組件的名稱
templateUrl: './app.component.html', //html
styleUrls: ['./app.component.scss'] //css
})
export class AppComponent {
title = 'angulardemo01'; //定義屬性
constructor(){ //構造函數
}
}
自定義組件
https://cli.angular.io
- 創建組件:
ng g component components/textcomponents
- 解釋:
ng g 表示自動創建一個組件 在app下的那一個文件夾下 / 組件名稱
- 使用這種方式創建組件,組件會自動註冊到
app.module.ts
;如果想要使用這個組件只需要找到新創建的組件的XXXX.component.ts中會有一個selector屬性;屬性後面的就是這個組建的名稱 - 在需要顯示組件的頁面使用一段標籤的的形式書寫selector中的組件名如:
<app-textcomponents></app-textcomponents>
刪除組件
- 刪除單個組件文件夾
- 在
app.module.ts
文件夾中將對應註冊的組價移除
將組件中的數據渲染在頁面上
-
在組建的ts文件中的
export class .......
中使用public 修飾變量名-
export class HomeComponent implements OnInit { public title = "這是首頁組件的數據,相當於vue中data中的數據" public title2 = "這是首頁組件的數據,相當於vue中data中的數據" constructor() { } ngOnInit() { } }
-
-
在頁面中直接可以使用插值表達式來渲染數據
{{title2}}