Angular CLI — Part II: Generating Components, Directives, Pipes and Services
This is the part II of the Angular CLI tutorial. By now you should have an Angular project created using cli, running at localhost:4200. Click here in case if you missed a step or want to refer to part I of this tutorial.
Assuming that you have followed part I and created same project as mentioned navigate to “ang-cli-proj“.
Create a new component
ng generate component my-new-component
This will create four files under src/app/my-new-component:
- my-new-component.component.css — Stylesheet
- my-new-component.component.html — Template
- my-new-component.component.spec.ts — Test specifications
- my-new-component.component.ts — Controller
And it will also update the app.module.ts automagically to include the new component.
Adding the newly created component to the template
Copy paste the below code to “app.component.html” under the H1 tag. Run the application using “ng serve”
<app-my-new-component></app-my-new-component>
You should see “my-new-component works!” under the title of the page.
By default angular cli will create all the scaffold’s under src/app folder. You can control this path by following examples as shown on Angular CLI site:
ng generate component my-new-component ng g component my-new-component # using the alias # components support relative path generation # if in the directory src/app/feature/ and you run ng g component new-cmp # your component will be generated in src/app/feature/new-cmp # but if you were to run ng g component ../newer-cmp # your component will be generated in src/app/newer-cmp # if in the directory src/app you can also run ng g component feature/new-cmp # and your component will be generated in src/app/feature/new-cmp
Scaffolding commands:
Component ng g component my-new-component
Directive ng g directive my-new-directive
Pipe ng g pipe my-new-pipe
Service ng g service my-new-service
Class ng g class my-new-class
Guard ng g guard my-new-guard
Interface ng g interface my-new-interface
Enum ng g enum my-new-enum
Module ng g module my-module
Resources:
- Official site: https://cli.angular.io/
- Github: https://github.com/angular/angular-cli
- Angular CLI wiki: https://github.com/angular/angular-cli/wiki
- npm cheatsheet: http://browsenpm.org/help#linkinganynpmpackagelocally