angular常用
1、提交表单的时候,触发表单验证
a、触发整个表单验证:this.form.markAllAsTouched();
b、触发指定单个表单元素验证:this.form.controls.name.markAsTouched();
2、angular11路由跳转:
a页面跳入b页面,在b页面获取元素距离顶部的距离,会发现值在a页面转入b页面之前就会调用
解决方法:在b页面设置settimeout延时去获取
3、获取网页地址参数
this.route.snapshot.queryParamMap.get('token')
route: ActivatedRoute
this.router.navigateByUrl('/refresh', {skipLocationChange: true}).then(()=>this.router.navigate(['/admin/category-save'], { queryParams: { 'pk': id } }));
4、Angular在组件中引入本地图片
<img src="assets/images/01.jpg">
ps:不需要写前面的../ 直接写assets
5、惰性加载,angular默认的加载方式是急性加载
例如:在app-routing.module.ts中写入:
export const routes: Routes = [
{ path: 'welcome', loadChildren: () => import('./pages/frontend/sign-in-copy/sign-in.module').then(mod => mod.SignInModule), data: { breadcrumb: 'Sign In ' } },
]
在sign-in .module.ts中写入:
export const routes = [
{ path: '', component: SignInComponent, pathMatch: 'full' }
];
6、Http拦截
Http拦截器就是拦截发出的请求,对其进行统一添加额外处理,然后放行;对响应进行拦截并作出业务上的判断,决定是否给与返回。
比如公共的api baseurl、header、是否需要携带token等
7、Json-server 在本地创建一个json文件,运行之后可以创建一个接口供测试使用
-[json-server] (https://github.com/typicode/json-server)
-1、安装 : 'npm i -g json-server'
-2、新建一个json文件 : 'db.json'
-3、在新建的json文件的目录下运行 json-server : 'json-server db.json'
ps:rest 常用的api:GET/POST/DELETE/PATCH
8、Angular httpClient获取请求头信息
const headers = new HttpHeaders(environment.otherRequestHeaders);
const httpOptions = {
headers: headers,
observe: "response" as 'body', // to display the full response
responseType: 'json' as 'json',
};
this.http.get(url,httpOptions).subscribe(res=>{
console.log(res);
});
9、Angular 路由
①路由跳转:
import { Router } from '@angular/router';
constructor(public router: Router){}
constructor(
this.router.navigateByUrl('/refresh', { skipLocationChange: true }).then(() => this.router.navigate(["/account/product-list"]));
②路由参数:
import { ActivatedRoute} from '@angular/router';
private activatedRoute: ActivatedRoute){}
this.activatedRoute
.paramMap
.subscribe(params => {});
10、路由高亮
<a routerLink="/home" routerLinkActive="actived">About</a>
css:
.actived{background:red}
精确匹配:
<a routerLink="/home" routerLinkActive="actived" [routerLinkActiveOptions]="{ exact:true }">About</a>
11、angular-material mat-select设置默认值:
<mat-select class="mat-select-custom" formControlName="affiliation" required > <mat-option value="">Please select</mat-option> <mat-option value="1">test</mat-option> </mat-select>
this.addAdminForm = this.formBuilder.group({ 'affiliation': ['', [Validators.required]] });

浙公网安备 33010602011771号