Angular
angular脚手架
npm install -g angular-cli
创建项目:ng new 项目名 //会安装依赖
ng new 项目名 --skip-install //不会安装依赖
HTML绑定:{{}}
属性绑定:[] 如vue中v-bind :
事件绑定:() 如vue中v-on @
事件名用()括起来,处理函数后必须有() (click):"add()"
for循环:*ngFor 如vue中的v-for
<ANY *ngFor="let 临时变量 of 数据">
样式绑定:ngClass="obj"
说明:ngClass绑定的值必须是一个对象!对象的属性就是CSS class名,属性值为true/false
true的话该class就出现,否则该class不出现。
使用双向数据绑定必须引入
import { FormsModule } from '@angular/forms' //记得挂载
全局样式
styles.css / styles/less / styles.scss
angular组件生命周期
ngOnChanges()
在 ngOnInit() 之前以及所绑定的一个或多个输入属性的值发生变化时都会调用。
注意,如果你的组件没有输入,或者你使用它时没有提供任何输入,那么框架就不会调用 ngOnChanges()。
ngOnInit()
在第一轮 ngOnChanges() 完成之后调用,只调用一次。 组件初始化完毕---相当于vue的mounted
ngDoCheck()
紧跟在每次执行变更检测时的 ngOnChanges() 和 首次执行变更检测时的 ngOnInit() 后调用。
ngAfterContentInit()
第一次 ngDoCheck() 之后调用,只调用一次。 组件内容初始化完成
ngAfterContentChecked()
ngAfterContentInit() 和每次 ngDoCheck() 之后调用
ngAfterViewInit()
第一次 ngAfterContentChecked() 之后调用,只调用一次。 组件视图初始化完成
ngAfterViewChecked()
ngAfterViewInit() 和每次 ngAfterContentChecked() 之后调用。 组件的视图发生变化需要检查
ngOnDestroy()
在 Angular 销毁指令或组件之前立即调用。
跨域 https://www.cnblogs.com/liuyuanfang/p/13361246.html
在根目录新建proxy.config.json文件写入 (网站上则是另一种写法)
{
"/api": {
"target":"http://127.0.0.1:20000/",
"secure": false,
"changeOrigin": true,
"logLevel": "debug"
}
}
一些angular行内样式
<h3 [style]="'background:red;color:#fff'"></h3>
<h3 [style]="{'background':'red','color':'#fff'}"></h3>
<h3 [ngstyle]="{'color':'red'}"></h3>
<h3 [ngstyle]="{'font-size' : isMax ? '24px' : '12px'}"></h3>
管道
创建一个管道ts
pipes文件下的test
ng g p pipes/test
在ts文件内的return后 '>>>'+value+'>>>'
去挂载上此ts的组件内{{ name | test }} //结果 >>>name>>>
时间管道
{{ time | date:'yyyy-MM-dd HH:mm:ss' }}
小写转大写 后转小写
{{ name | uppercase | lowercase }}
改变显示方法
|currency(保留小数点后两位 (有四舍五入)
|currency:“¥”(显示人名币)
默认是显示$ 如 1233268542.9786564567 // $1,233,268,542.98
|number保留三位小数 (有四舍五入)
过滤json
|json数据显示json格式
服务
ng g s XXX创建一个服务
ts内容
import { Injectable } from '@angular/core';
@Injectable({
//root表示注入到app.module.ts内, null,表示不设定区域, 还可以是某个模块的名字(一般就是懒加载模式)
//作用域设定
providedIn:'root'
})
export class ListService {
constructor() { }
}
不会自动导入,需要手动导入 app.module 引入 引入后在providers里注入
在组件中使用时 在ts里引入 引入后在constructor里注入 constructor(private name:name)
angular键盘事件
<div (keyup)="button($event)"></div> //html
button(e:any) {
console.log(e) //获取到进行了那些键盘事件
}
也可直接
(keyup.enter) //回车 后面直接跟函数
angular会话存储
public tags:any[] = JSON.parse(sessionStorage.getItem('tags') || JSON.stringify([{title:"我的",routerLink:"home"}]));
存进去的需要转换成string格式拿出来的时候在转需要的格式 在开辟空间存储时则要类似这样 不然会报错
非数组对象则随意
css样式文本不能被选中
user-select:none;
超出显示省略号
overflow: hidden;
text-overflow:ellipsis;
white-space: nowrap;
ngfor循环问题
报错 Can't bind to 'ngForOf' since it isn't a known property of 'div'.
在当前组件的module中添加 CommonModule
import {CommonModule} from '@angular/common';
下方imports中引入