目录
1、ng generate <蓝本名> 命令
2、Components 组件
3、Directive
4、Service
5、Model/Interface/Enum/Pipe
model
interface
enum
Pipe
Module
这篇文章主要是讲生成 Components, Directive, Service, class, interface, enum等等.
该命令的格式是 ng generate <蓝本名> <参数>.
也可以使用--dry-run参数来列出要生成的文件, 而不是真的生成.
例如:
ng generate component person, 就会生成一个名称为PersonComponent的组件
ng generate service sales-data, 就会生成一个名称为SalesDataService的服务
ng generate class user-model,就会生成一个名称为UserModel的类
ng generate xxx xxx的命令还是有点长, 这里angular cli内置了命令的别名, 例如:
ng generate component person 这个命令,
里面的generate 可以使用字母 g 代替,
里面的component 可以使用字母 c 代替.
所以这两个命令是相等的:
ng generate component person
ng g c person
可以到这里查看component相关的命令和别名:
https://github.com/angular/angular-cli/wiki/generate-component
可能常用的命令参数有:
看下面两对作用相同的命令, 还是使用别名方便:
ng generate component person
ng generate component person --inline-template --inline-style
ng g c person
ng g c person -it -is
下面来试试这些命令:
ng new my-app --style scss --skip-install --routing
cd my-app
cnpm install
ng g c person -d
该命令将会生成上述4个文件, 并更新app.module.ts.
下面把-d参数去掉, 生成文件:
可以看到文件生成在项目里了. 并且更新了app.module.ts, 在里面做了component的声明.
再试试生成另外一个component:
ng g c student
通过源码管理页, 可以看到这两个命令对app.module进行了哪些更新:
分别对生成的两个component进行了声明.
修改app-routing.module.ts
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { PersonComponent } from './person/person.component';
import { StudentComponent } from './student/student.component';
const routes: Routes = [
{path: 'person', component: PersonComponent},
{path: 'student', component: StudentComponent},
{path: '', redirectTo: '/person', pathMatch: 'full'}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
引入两个组件,在路由数组中定义两个url以及空的url。
启动项目试试
在vs code中打开终端,输入 ng serve -o (或者 ng serve -open )
ng g d filter-box -d
这是文件报告, 下面真正的生成:
ng g d filter-box
通过vscode的源码管理, 可以看到变化:
directive生成了两个文件和component一样, 也在app.module进行了声明.
生成的directive的结构是没有目录, 也就是flat的.
如果不想生成flat样式的, 想让其拥有自己的文件夹, 那么就是用--flat参数:
ng g d filter-box2 --flat false
ng g s order-data -d
然后把-d去掉, 真实生成文件:
ng g s service/order-data
在service文件夹下面,只生成了两个文件, 并没有在app.module里面注册。
当然可以在这里写代码把刚才生成的service注册进去.
ng g cl models/user
这个命令会创建models文件夹, 然后在里面创建use的model。
ng g i models/animal
ng g e models/gender
ng g p camel-case
ng g m login
ng g c login/welcome -m login