generating angular base files using angular-cli
while building a new angular application, we create tens of components, services, classes etc. if using angular-cli, this repetitive task becomes so very easy to do.
with ng generate
command, we can create blueprint for all kind of resources needed during the course of our angular application development. this makes life easy as a developer as we can focus on the core of what we are building, saving a lot of time from doing the obvious.
let’s quickly look into how it works.
to create any kind of resource, we provide ng generate
command with the resource type and resource name and we have all the necessary files generated for that kind of resource.
say, we want to create a new component, foo-component
, the command that we write is
ng generate component foo-component
and we have a new folder foo-component
with the files that a typical component needs:
- foo-component.component.ts — component class file
- foo-component.component.html — component template
- foo-component.component.css — component styles
- foo-component.component.spec.ts — unit tests for the component
also, this new component gets added in your default module declarations automatically ( see--skip-import
below to override this behaviour).
you also have some handy options to use while using ng generate
. some important, frequently used ones are —
--flat
— if provided, the files will be created without a directory. useful while creating a global service for example.--module
— the module that the new component should be declared into. eg. when you have two modules present in your root directory and you try to generate a new component, you will get an error like below:
Error: More than one module matches. Use skip-import option to skip importing the component into the closest module.
here, you can provide a --module=<target-module>
and the component is generated, declared into correct module.
--skip-import
— as you see in the error above, another way to avoid this error would be to use--skip-import
option. the component would be generated the same way, except it would not be declared into any module automatically, which you could do manually later.--prefix
— the prefix name to use in component selector or to not use a prefix at all. eg.
ng generate component foo-component --prefix=bar
this will generate the component with selector name as bar-foo-component
.
--spec
— if provided with--spec=false
the spec test file will not be generated.
these were some of the important options that could be handy while developing an angular app and using angular-cli along the way.