本周使用angular7所遇到的一些问题

前言

本周在使用angular7所遇到的一些问题,学习是不断的循序渐进的过程,在本周完成对应的工作后,也要抽出一些时间用来学习,比较我们公司10点上班,我一般9点就会到,在这一个小时内看看博客,写写笔记,学习下angular7,antd框架的一些问题,

打包问题

angular.json

     "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist",   //去掉 dist/后面对应的东西

package.json
  "build": "ng build --prod --build--optimizer "    
              
index.html
     <base href="/">  //跟后台确定好服务器的地址并且填在这里

反向代理

在根目录新建 proxy.config.json

{
  "/api": {
    "target": "http://a.itying.com",
    "secure": "false",
    "changeOrigin": true
  }
}

package.json

"start": "ng serve --proxy-config proxy.conf.json", 
    
//注意使用 npm run start 或者使用 yarn start  
//我犯了一个错误使用 ng serve  一直报错总是不知道原因
//使用的时候
/api/productlist   //地址头部为 /api就行啦

使用 ng-zorro-antd

首先说一下angular7对新手很不友好,建议学习的时候尽量按照vue的思路去想问题,然后再考虑angular7是怎么实现的,因为国内ng的资料实在太少

ng  add ng-zorro-antd
//建议使用less,我使用scss一直报错,都懵逼的不知道原因
//如果使用scss用全局配置下node-sass的镜像下载
修改默认使用yarn 下载
ng config -g cli.packageManager yarn
//如果让yarn支持 node-sass
yarn config set sass-binary-site http://npm.taobao.org/mirrors/node-sass
第一个y 图标
第二个n  选择cn
不行的话就cnpm  install node-sass

或者直接使用
ng new static --style less
cd static
ng add ng-zorro-antd

angular-cli升级

# 卸载现有angular-cli
npm uninstall -g angular-cli
# 清空cache
npm cache clean -f
# 升级
npm install -g @angular/cli@latest
# 升级到固定版本号
npm install -g @angular/cli@版本号 

使用ng-zorro-antd的样式

::ng-deep 改样式

导入第三方库

angular.json
styles中就是我们要引入的css
scripts中就是我们要引入的js
详细配置文件解释
https://www.jianshu.com/p/1c3d13af4f88

我是这样使用的
yarn add axios -S

import * as axios from 'axios'
//暂时还没发现报错

//下面还有一个标准的例子
cnpm install qs -S
cnpm install @types/qs -S
在angular.json引入
 "scripts": [
              "./node_modules/qs/dist/qs.js"
            ],
在 tsconfig.app.json引入
"types": ["qs"]
所在的组件.ts
import * as qs from 'qs';   
 console.log(qs.stringify({name: 'age', age: 12}));

封装http

把公共的部分放在服务里面

  get(api, params = {}) {
    return new Promise((resolve, reject) => {
      const getString: string = api + qs.stringify(params);
      this.http.get(getString).subscribe((response) => {
        resolve(response);
      }, (rej) => reject(rej));
    });
  }

  post(api, params = {}) {
    return new Promise((resolve, reject) => {
        const httpOptions = {
             headers: new HttpHeaders({ 'Content-Type': 'application/json;application/x-www-form-urlencodeed; charset=utf-8'})
        };
      const postString: string = api + qs.stringify(params);
      this.http.post(postString, httpOptions).subscribe(response => {
        resolve(response);
      }, rej => reject(rej));
    });
  }

ng-zorro 布局篇

    <div nz-row>
      <div nz-col nzSpan="12">col-12</div>
      <div nz-col nzSpan="12">col-12</div>
    </div>
父盒子带有 nz-row 子盒子带有nz-col,因为24栅格,nzSpan="6"

栅格常常需要间隔 nzGutter
父元素
<div nz-row nzGutter="16">  推荐 8n+8
 
左右偏移
子盒子   nzoffset="4"

ng-zorro Flex布局

父元素添加 nzType="flex"
水平方向  nzJustify=""  start,center,end,space-between,space-around
<div nz-row nzType="flex" nzJustify="start">
        <div nz-col nzSpan="4">col-4</div>
垂直方向 nzAlign=""  top  middle  bottom
 <div nz-row nzType="flex" nzJustify="space-around" nzAlign="middle">

在使用路由默认处于激活的状态

<a routerLink="/a/b" routerLinkActive="active" [routerLinkActiveOptions]="{exact:
true}">B链接</a>

https://majing.io/posts/10000019031169

表单

说实话表单这块内容有时候会让你感觉到头大

个人首先过一遍官网的表单,然后再来学antd的表单

(ngModelChange)="add()" 监控input的状态
//提交
<form nz-form [formGroup]="validateForm"
      (ngSubmit)="submitForm($event, validateForm.value)">
 提交
   submitForm = ($event: any, value: any) => {
    $event.preventDefault();
    for (const key in this.validateForm.controls) {
      this.validateForm.controls[key].markAsDirty();
      this.validateForm.controls[key].updateValueAndValidity();
    }
    console.log(value);
  };
重置状态

resetForm(e: MouseEvent): void {
    e.preventDefault();
    this.validateForm.reset();
    for (const key in this.validateForm.controls) {
      this.validateForm.controls[key].markAsPristine();
      this.validateForm.controls[key].updateValueAndValidity();
    }
  }

<input formControlName="password" //填写双向绑定的参数>

备注框
  <textarea formControlName="comment" nz-input rows="2" placeholder="write any thing">
最后的提交按钮和重置按钮
  <nz-form-item>
    <nz-form-control [nzOffset]="7" [nzSpan]="12">
      <button nz-button nzType="primary"
              [disabled]="!validateForm.valid">Submit
      </button>
      <button nz-button (click)="resetForm($event)">Reset</button>
    </nz-form-control>
  </nz-form-item>

学习的时候看的,不然太多了,你会不理解

<form nz-form  [formGroup]="validateForm" (ngSubmit)="submitForm()">
      <nz-form-item>
         <nz-form-label [nzSm]="8" nzRequired>密码</nz-form-label>
         <nz-form-control>//表单域
             <input nz-input formControlName="userName" placeholder="提示的信息" />
             <nz-form-explain *ngIf="validateForm.get('userName')?.dirty &&                     validateForm.get('userName')?.errors" >我是错误的信息</nz-form-explain>
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
 validateForm: FormGroup;
  submitForm(): void {
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
      this.validateForm.controls[i].updateValueAndValidity();
    }
  }
  constructor(private fb: FormBuilder) {}
  ngOnInit(): void {
    this.validateForm = this.fb.group({
      userName: [null, [Validators.required]],
      password: [null, [Validators.required]],
      remember: [true],
                email: [null, [Validators.required,Validators.pattern(/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/)]],
//正则验证
                    函数判断
      confirm: ['', [this.confirmValidator]],           
    });
  }
   confirmValidator = (control: FormControl): { [s: string]: boolean } => {
    if (!control.value) {
      return { required: true };
    } else if (control.value !== this.validateForm.controls.password.value) {
      return { confirm: true, error: true };
    }
    return {};
  };

猜你喜欢

转载自www.cnblogs.com/fangdongdemao/p/10885532.html