YellowFish
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Note Insights Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    ###### tags: `server` # [Angular前端框架](https://developer.mozilla.org/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Angular_getting_started) ## 1. [安裝Visual Studio Code](https://www.golinuxcloud.com/install-visual-studio-code-rocky-linux/) ``` $ sudo rpm --import https://packages.microsoft.com/keys/microsoft.asc $ sudo sh -c 'echo -e "[code]\nname=Visual Studio Code\nbaseurl=https://packages.microsoft.com/yumrepos/vscode\nenabled=1\ngpgcheck=1\ngpgkey=https://packages.microsoft.com/keys/microsoft.asc" > /etc/yum.repos.d/vscode.repo' $ sudo dnf check-update $ sudo dnf -y install code ``` ## 2. [安裝Angular](https://www.atlantic.net/dedicated-server-hosting/how-to-install-angularjs-on-rocky-linux-8/) * ### 安裝nodejs ``` $ sudo dnf update -y $ sudo dnf install curl -y $ curl -sL https://rpm.nodesource.com/setup_14.x | bash - *若這行指令出現Permission Denied錯誤,先切換到su再執行就好,之後記得exit退出root $ sudo dnf install nodejs -y $ node -v (確認nodejs版本) ``` * ### 更新npm ``` sudo npm install npm@latest -g npm --version (確認npm版本) ``` * ### 安裝Angular CLI ``` sudo npm install -g @angular/cli ng version (確認Angular版本) 這時會出現以下畫面: ? Would you like to enable autocompletion? This will set up your terminal so pressing TAB while typing Angular CLI commands will show possible options and autocomplete arguments. (Enabling autocompletion will modify configuration files in your home directory.) Yes Appended `source <(ng completion script)` to `/home/kenny/.bashrc`. Restart your terminal or run the following to autocomplete `ng` commands: source <(ng completion script) ? Would you like to share pseudonymous usage data about this project with the Angular Team at Google under Google's Privacy Policy at https://policies.google.com/privacy. For more details and how to change this setting, see https://angular.io/analytics. No *輸入Yes和No ``` ## 3. 開始使用Angular * ### 建立新專案 ``` $ ng new firstapp 這時會出現以下畫面: ? Would you like to add Angular routing? Yes ? Which stylesheet format would you like to use? (Use arrow keys) ❯ CSS SCSS [ http://sass-lang.com/documentation/file.SASS_REFERENCE.html#syntax ] Sass [ http://sass-lang.com/documentation/file.INDENTED_SYNTAX.html ] Less [ http://lesscss.org ] Stylus [ http://stylus-lang.com ] *輸入Yes和css ``` * ### 啟動專案 ``` $ cd firstapp $ ng serve * 根據使用的port,在瀏覽器輸入localhost:{server port}就可以看到首頁(index.html)了 * 使用 $ ng serve --open的話會在建置後自動開啟瀏覽器(較方便) ``` ## 4. Angular簡介 * ### 在建立Angular專案之後,在firstapp/src裡會出現app資料夾,其中有5個主要檔案: 1. **app.module.ts**: 列出這個專案使用的所有檔案 2. **app.component.ts**: 處理專案主要頁面的**邏輯** 3. **app.component.html**: 處理專案主要頁面的**畫面** 4. **app.component.css**: 處理專案主要畫面的**樣式** 5. **app-routing.module.ts**: 處理專案的路由(建置專案時add routing選Yes才會出現,也可之後再新增,新增指令: ```$ ng generate module app-routing --flat --module=app```) * ### Angular運作方式: 1. 整個畫面只在index.html上顯示,其他元件(Component)都是利用路由導入進去 2. index.html: ```html=1 <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>Firstapp</title> <base href="/"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="icon" type="image/x-icon" href="favicon.ico"> </head> <body> <app-root></app-root> </body> </html> ``` *第11行body導入了app-root這個元件,而app-root這個元件是由初始app元件的component.ts所定義的 3. component.ts: ```typejavascript=1 import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'firstapp'; } ``` *3,4,5行分別定義了這個元件導入時的element名稱,這個元件的html存放位置,這個元件的css存放位置 4. 當我們打開index.html,index.html當中讀取到app-root這個元件時便會去導入app.component.ts中的selector定義的元件,它的html畫面以及它的css樣式 ## 5. 元件導入首頁 * ### 新增元件 當我們想在專案下新增功能時,不會把邏輯全部寫在app.component.html,通常會寫在app.component.ts,也可以新增一個元件,然後直接將該元件的selector名稱加到app.component.html,或是透過路由將該元件導入app的畫面 ``` 新增元件指令: $ ng generate component todo-page $ ng g c tode-page *上下兩者相同 ``` 新增todo-page元件後,首頁並不會有任何改變,原因是todo-page並沒有被放進首頁,必須設定路由把它導入首頁 ### (1) 直接加進app.component.html * #### 開啟todo-page.component.ts查看selector的名稱 ```javascript=1 import { Component } from '@angular/core'; @Component({ selector: 'app-todo-page', templateUrl: './todo-page.component.html', styleUrls: ['./todo-page.component.css'] }) export class TodoPageComponent { } ``` *第4行定義該元件的selector名稱為'app-todo-page',若要導入這個元件,就在html中輸入這個名稱的元素 * #### 修改app.component.html,內容如下: ```html=1 <app-todo-page></app-todo-page> ``` 儲存後就能看到網頁長這樣: ![](https://i.imgur.com/TOOUS6v.png) ### (2) 設定路由 * #### 修改app-routing.modules.ts,內容如下: ```typejavascript=1 import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { TodoPageComponent } from './todo-page/todo-page.component'; const routes: Routes = [ { path: "", component: TodoPageComponent } ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { } ``` * #### 修改畫面(app.component.html) 接著修改app.component.html,內容如下: ```html=1 <router-outlet></router-outlet> ``` 儲存後就能看到網頁長這樣: ![](https://i.imgur.com/TOOUS6v.png) ## 6. 建置待辦事項系統 ### (1) 定義Item(事項) * #### 在app資料夾下新增job.ts,內容如下: ```ts=1 export interface job { title: string; date: Date; content: string; done: boolean; } ``` * 這裡定義了事項的4個屬性title(標題)、date(日期)、content(內容)、done(是否完成),它們的型態分別為string、string、string、boolean ### (2) app.component.html定義系統畫面 ```html=1 <h1>Todo List</h1> <h2>Create Job</h2> <input #myTitle placeholder="job title"/> <input type="date" #myDate/> <input #myContent placeholder="job content"/> <button (click)="addJob(myTitle.value,convertDate(myDate.value),myContent.value); myTitle.value='';myDate.value='';myContent.value=''">Create</button> <table> <tr><td>title</td><td>date</td><td>content</td></tr> <tr *ngFor="let i of myJob"><td>{{i.title}}</td><td>{{i.date}}</td><td>{{i.content}}</td><td><button (click)="removeJob(i)">Delete</button></td><app-edit-job [theJob]="i"></app-edit-job></tr> </table> <input #searcher placeholder="job title/date/content"/> <button (click)="search=searcher.value">search</button> <button (click)="search='';searcher.value=''">reset</button> ``` * 第2行開始是添加新增事項功能,按下第6行的button就會把輸入的欄位值回傳給app.component.ts執行addJob(新增事項)函式,然後欄位復原成空值 * 由於日期是date型態,但html中的欄位.value會轉成字串型態,所以要再使用convertDate()函式轉回date型態 * 第7行開是顯示目前所有事項,利用*ngFor將app.component.ts傳來的myJob陣列內的值依序執行迴圈 * 按下第9行後面的button就會回傳myJob[i]這個事項給app.component.ts來執行remove(刪除事項)函式 * 第9行最後面有一個<app-edit-job></app-edit-job>>區塊,這是從另一個元件導入的,會放到第4點說明 * 第11行開始是查尋事項功能,按下search會將欄位輸入值更改到app.component.ts中的search ### (3) app.component.ts定義系統邏輯 ```typejavacript=1 import { Component } from '@angular/core'; import { job } from './job'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'firstapp'; // defined filter words search = ""; // defiend job allJobs = [ {title:"hello",date: new Date("2023-01-01"),content:"say hello",done:false}, {title:"goodbye",date:new Date("2023-01-02"),content:"say goodbye",done:false}, ] // display job to html get myJob() { if (this.search=="") { return this.allJobs; } let filter = this.search; let filterJobs = this.allJobs.filter(function(allJob) { return (allJob.title === filter || allJob.content === filter); }); return filterJobs; } // function addJob addJob(title: string, date:Date, content: string) { if (title=="" || date.toString()=="Invalid Date" || content=="") { alert("please fill in all filed!"); return; } this.allJobs.push({ title, date, content, done: false }); } // function removeJob removeJob(theJob: job) { this.allJobs.splice(this.allJobs.indexOf(theJob),1); } convertDate(date: string) { return new Date(date); } } ``` * 第2行根據檔案路徑導入前面創造的事項物件(job.ts) * 第12行定義了搜尋欄位的值search,初始值為空字串 * 第14行定義了系統開啟後就會存在的所有事項allJobs,每個事項的屬性都依照job.ts定義的事項屬性 * 第19行的get myJob()是一個getter,會將該函式的值回傳給html,這裡會根據search的值決定要回傳全部事項,還是只回傳符合條件的事項,回傳的東西都叫做myJob * 第30行的addJob定義新增事項功能函式,首先要檢查欄位是否都輸入,若有欄位是空的就發出alert並直接return * 因為日期欄位若沒填,傳過來的值會是date型態的"Invalid Date",所以要先轉成字串再比較 * 第35行若欄位都有填,就會把這個事項push(放到最後面)到allJobs裡,另外也可以用unshif(放到最前面)) * 第43行的removeJob定義刪除事項功能函式,利用splice函式比對參數的事項在所有事項的index值,並從該index值開始刪除陣列中的一個值 * 第46行的convertDate定義了字串轉成date的型態轉換 ### (4) 新增元件來完成編輯事項功能 * 先用以下指令新建元件 ``` $ ng g c edit-job ``` * 在edit-job.component.ts中的@Component區塊,可以看到selector屬性中的值是'app-edit-job',這代表我們若要在其他html中導入edit-job這個元件,就要建立這樣的區塊: <app-edit-job></app-edit-job> ```typejavascript=1 @Component({ selector: 'app-edit-job', templateUrl: './edit-job.component.html', styleUrls: ['./edit-job.component.css'] }) ``` ### (5) edit-job.component.html定義元件畫面 ```html=1 <div *ngIf="!display"> <button (click)="display=!display">Edit</button> </div> <div *ngIf="display"> <input #myTitle placeholder="job title"/> <input type="date" #myDate/> <input #myContent placeholder="job content"/> <button (click)="editJob(myTitle.value,convertDate(myDate.value),myContent.value); myTitle.value='';myDate.value='';myContent.value=''">Edit</button> <button (click)="display=!display">Cancel</button> </div> ``` * 第1行利用*ngIf判斷display的值來決定是否要顯示Edit(編輯事項)按鈕而是,還是顯示編輯事項的所有欄位 * 若display的值為false,會只顯示Edit按鈕給此用者點擊,以開始編輯事項 * 若display的值為true,代表使用者已經按下Edit按鈕,這時就要顯示所有事項欄位讓使用者填寫 * 按下第9行的button就會把輸入的欄位值回傳給edit-job.component.ts執行EditJob(編輯事項)函式,然後欄位復原成空值 * 由於日期是date型態,但html中的欄位.value會轉成字串型態,所以要再加convertDate()函式轉回date型態 * 按下第10行的button就會透過修改display的值,達到隱藏所有欄位並只顯示Edit按鈕的效果 ### (6) edit-job.component.ts定義元件邏輯 ```typejavascript=1 import { Component, Input } from '@angular/core'; import { job } from '../job'; @Component({ selector: 'app-edit-job', templateUrl: './edit-job.component.html', styleUrls: ['./edit-job.component.css'] }) export class EditJobComponent { // defined job which is Input from other file @Input() theJob!: job; // defined display display = false; // edit the job editJob(title: string, date:Date, content: string) { if (title=="" || date.toString()=="Invalid Date" || content=="") { alert("please fill in all filed!"); this.display=false; return; } this.display = false; this.theJob.title=title; this.theJob.date=date; this.theJob.content=content; } convertDate(date: string) { return new Date(date); } } ``` * 第2行根據檔案路徑導入前面創造的事項物件(job.ts) * 第11行用@Input()導入app.component.html中(第9行<app-edit-job [theJob]="i"></app-edit-job>)傳來的allJob[i](for迴圈依序執行的事項),傳過來的事項名稱就叫做theJob * 第13行定義了是否顯示欄位的值display,初始值為false * 第15行的editJob定義編輯事項功能函式,首先要檢查欄位是否都輸入,若有欄位是空的就發出alert並直接return * 因為日期欄位若沒填,傳過來的值會是date型態的"Invalid Date",所以要先轉成字串再比較 * 第21行若欄位都有填,就會把這個事項的值改成使用者輸入的值,並把display設成false,這樣使用者在送出編輯內容後,這些欄位就不會顯示了 * 第26行的convertDate定義了字串轉成date的型態轉換 ### (7) 編譯並開啟系統畫面 * 輸入以下指令編譯並開啟瀏覽器4200port ``` $ ng serve --open ``` * 待辦事項系統完成了!(這邊IP打192.168.31.245是因為下面步驟的設定) ![](https://i.imgur.com/xBgSrTg.png) ## 7. 開放其他主機連線到Angular伺服器 ### (1) 開放防火牆4200port * 輸入以下指令確認4200 port是否被開放 ``` $ sudo firewall-cmd --list-ports ``` * 若沒被開放,輸入以下指令開放 ``` $ sudo firewall-cmd --add-port=4200/tcp --permanent ``` * 重新套用防火牆設定 ``` sudo firewall-cmd --reload ``` ### (2) 以虛擬機IP位址開啟angular伺服器 * 用以下指令開啟angular伺服器(以虛擬機IP為192.168.31.245為例) ``` $ ng serve --host 192.168.31.245 ``` ### (3) 本機連線到虛擬機上的angular * 本機開啟瀏覽器並輸入http://192.168.31.245:4200,就能看到剛才做好的待辦事項系統畫面了 ![](https://i.imgur.com/FYCBNCk.png)

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully