Angular 4 - The Basics 笔记(2): Component
-
How to create a new component manually
- create folder for your component: /src/app/yourComponent
- create ts and html file: /src/app/yourComponent/name.component.ts & name.component.html
- 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{ }
- edit name.component.ts
- 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>
- edit app.component.html