[Angular] 自建custom component

Angular Component 類似WinForm / WPF 的User control, 將一個會重覆使用的markup 抽出成獨立個體, 並於不同地方使用. 從而加快develop / change 速度.

在這裡, 會以建立一個layout component 示範如何建立custom component.

有關的Project structure 如下:

2016-12-06-14_00_37-pc0238v-vs2015-vmware-workstation

  1. 於/app/theme/ 中, 建立TypeScript file, 命為layout.component.ts, 並輸入以下內容:
    import { Component, Input } from '@angular/core';
    
    @Component({
        moduleId: module.id,
        selector: 'layout',
        templateUrl: 'layout.component.html'
    })
    export class LayoutComponent {
         
    }
    
  2. 為了將 UI和 logic分開, 於/app/theme/ 中, 建立TypeScript file, 命為layout.component.html, 此為custom component 的markup, 並輸入以下內容:
    <h1>This is a theme in HTML file.</h1>
  3. 開啟/app/aoo.module.ts, 登記於step 1 中建立的component. 於import 後便於declarations 加入.
    import { NgModule }      from '@angular/core';
    import { BrowserModule } from '@angular/platform-browser';
    import { FormsModule, ReactiveFormsModule }   from '@angular/forms';
    import { AppComponent }  from './app.component';
    import { LayoutComponent } from './theme/layout.component';
    
    @NgModule({
        imports: [BrowserModule, FormsModule, ReactiveFormsModule],
        declarations: [AppComponent, LayoutComponent],
        bootstrap: [AppComponent]
    })
    export class AppModule { }
    
  4. 之後於/app/app.component.ts 中調用以作測試.
    import { Component } from '@angular/core';
    
    @Component({
        selector: 'my-app',
        template: '<layout></layout>'
    })
    export class AppComponent {
    
    }
    
  5. 之前在tsconfig.json中已設定save 後自行再編譯js file; 若沒有的話, 自行用tsc command 編譯;
  6. 於Visual Studio 中執行. 於瀏覽器中見到以下的結果視為成功.
    2016-12-06-13_55_46-pc0238v-vs2015-vmware-workstation

Reference

About C.H. Ling 260 Articles
a .net / Java developer from Hong Kong and currently located in United Kingdom. Thanks for Google because it solve many technical problems so I build this blog as return. Besides coding and trying advance technology, hiking and traveling is other favorite to me, so I will write down something what I see and what I feel during it. Happy reading!!!

Be the first to comment

Leave a Reply

Your email address will not be published.


*


This site uses Akismet to reduce spam. Learn how your comment data is processed.