一、安装
module load ossjs/node/8.11.1 //load Node.js
npm install -g @angular/cli
ng version //angular version
npm run start // run the application locally 通过在package.json文件中修改start对应脚本来改变host和port
二、常用命令
1) ng help
2) ng new (create a new project)
a. –dry -run: 开发辅助,走一遍创建流程而不进行实际项目的创建
b. –prefix: 修改默认值
c. –routing: routing module
3) ng serve (run the project)
a. –port: change the port
4) ng generate (generate component, service and so on)
a. ng g component test: 添加前端组件,得到的组件可以直接通过标签加入大组件中
b. ng g service test -m app.module.ts: 添加后端组件,将service注册到app-module里
5) ng test (for test)
a. 代码中可加入expect(…).toEqual(…)作为判断语句,在测试时会进行检测
6) ng build (release, save the compiled modules to the local package ‘dist’)
a. ls -alh dist/: 查看文件目录下的文件详情
b. du -h dist/: 查看目录大小
c. ng build –aot: 压缩项目体积
d. ng build –prod: ng build默认为开发模式, 添加–prod切换为生产模式
三、使用方法
1. 至少需要一个模块作为启动模块,常命名为app.module.ts。
2. BrowserModule包含浏览器上启动应用的关键逻辑,main.ts包含启动代码。index.html中需要引入定义的组件
3. 内置指令:允许创建自定义标签
a. nglf: 由条件来决定显示或者隐藏元素;
b. ngSwitch:根据给定条件渲染不同的元素,方法和java中的switch类似,*ngSwitchCase/*ngSwitchDefault
c. ngStyle:通过Angular表达式给特定的DOM设定CSS属性,[style.]=”value”
d. ngFor: “let item of items”,重复一个给定的DOM元素,每次重复从数组中去一个不同的值。
e. 。。。
4. 服务使用:常用LoggerService做调试的信息输出,需要在app.module.ts中注入加入providers中,并在app.component.ts中注入,加入构造函数并进行输出调试。
父子组件间通讯:
a. 父组件得到子组件的数据
i. 子组件:在search-button组件中进行search请求,请求中调用service服务获得数据 (需要考虑请求的接口以及返回的内容形式),通过@Output将event定义为输出属性,并使用upward进行向上传递
ii. 父组件:search-page中监听自定义事件event,通过调用getClientData来接收传递过来的数据并进行打印。
b. 子组件得到父组件的数据
i. 子组件:使用@Input定义需要从父组件获取的变量
ii. 父组件:在调用子组件时将对应需要传递的变量进行传递
路由:可以控制不同的path下进入不同的页面,进行页面跳转;children对应的当前component下的子组件,可以通过routerlink进行相应子组件的加载 (在当前页面component上的加载,额外增加的部分,而不是新的页面)
exportconstroutes:Routes=[
{path:”,component:HomePageComponent},
{path:’searchPage’,component:SearchPageComponent,
children:[
{path:’mainContent/:id’,component:SearPageMainContentComponent}
]},
//{path:”,component:SearchPageComponent}
];
exportconstrouting:ModuleWithProviders=RouterModule.forRoot(routes);
调取service获取的数据传递到对应组件的问题:
1)service部分只需直接return http.get的内容即可,返回的数据为Observable格式
2)调用service的组件可以使用subscribe将data转化到对应的数据格式并且赋值给当前component中的数据对象。
控制一个div模块不显示也不占用空间,给div设置id并使用:
document.getElementById(“main-content”).style.display=”none”;
当用户点击search按钮后,将result显示,也就是将对应div模块设置为显示:
完成数据接收后在subscibe语句中添加
document.getElementById(“main-content”).style.display=”block”;
这样不会有初始化错误问题,也能够保证在http.get之后进行模块显示的操作。
Error: If ngModel is used within a form tag, either the name attribute must be set or the form control must be defined as ‘standalone’ in ngModelOptions.
solution:需要在对应位置添加name属性,用于在表单中的注册。