Angular 4 - The Basics 笔记(2): Component

  • How to create a new component manually

  1. create folder for your component: /src/app/yourComponent
  2. create ts and html file: /src/app/yourComponent/name.component.ts & name.component.html
    1. edit name.component.ts
      //add component function
      import {Component} from '@angular/core';
       
      //config this component for angular
      @Component({
          selector: 'app-name', //html tag <app-name></app-name>
          selector: '[app-name]' //attribute <div app-name></div>
          selector: '.app-name' //class <div class="app-name"></div>
      
          templateUrl: './name.component.html', //external html file
          template: '<h1>hello</h1>', //or use inline html
      
          styleUrls: '['./name.component.css']', //externam css file
          styles: ['p{color: darkblue}'], //inline style
      
      })
      
      //normal typescript class
      export class NameComponent{
         
      }

       

       

       

       

  3. edit /src/app/app.module.ts
    //tell typescript where to find it, no need for .ts extendsion
    import { NameComponent } from './yourComponent/name.component';
    
    @NgModule({
      declarations: [
        AppComponent,
        //tell angular we have a new component to use
        NameComponent
      ],

    

  • How to create a component from CLI

    • ng generate component name
      
      or
      
      ng g c name

       

       

  • How to use component

    •   edit app.component.html
      <app-header></app-header>
      <div app-name></div>
      <div class="app-header"></div>

       

       

       

    

 

posted @ 2017-05-03 17:27  Hardi  阅读(158)  评论(0编辑  收藏  举报