Angular8的使用(九):组件的使用(积累)

1.ngx-loading组件

使用加载提示组件

1.1.安装命令

npm install --save ngx-loading

1.2.引入组件

在app.module.ts中添加:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { NgxLoadingModule } from 'ngx-loading'; // 引入

@NgModule({
  ...
  imports: [
    ...
      NgxLoadingModule, // 引入
    ...
  ],
 ...
})
export class AppModule { }

1.3.其他组件中调用

1.3.1.HTML代码

<ngx-loading [show]="downLoading" [config]="{ backdropBorderRadius: '3px' }"></ngx-loading>

1.3.2.ts代码

import { Component, OnInit } from '@angular/core';
@Component({
})
export class AppComponent implements OnInit {
    public downLoading = false;
 
    constructor(private as: Service) { }
 
    ngOnInit() { }
 
    downFile() {
        this.downLoading = true;
        this.as.test().subscribe(res => {
                this.downLoading = false;
        }, err => {
               this.downLoading = false;
        });
    }
}

文章来自于: ngx-loading官网.

2.ngx-echarts组件

2.1.安装

npm install echarts --save
npm install ngx-echarts --save

2.2.引入组件

在app.module.ts中添加:

import { NgxEchartsModule } from 'ngx-echarts'; // 引入

@NgModule({
  imports: [
    ...,
    NgxEchartsModule.forRoot({
      echarts: () => import('echarts') //使用此方式引入
    })
  ],
})
export class AppModule { }

2.3.BUG问题

2.3.1.装饰器不支持函数表达式错误:

Function expressions are not supported in decorators
Consider changing the function expression into an exported function.

则使用下面的引入:

import { NgxEchartsModule } from 'ngx-echarts';
import * as echarts from 'echarts';
 
@NgModule({
  imports: [
    NgxEchartsModule.forRoot({
      echarts,
    }),
  ],
})
export class AppModule {}

2.3.2.Cannot destructure property init

TypeError: Cannot destructure property 'init' of 'object null' as it is null
这个时候需要使用:

import { NgxEchartsModule } from 'ngx-echarts';
import * as echarts from 'echarts';
 
@NgModule({
  imports: [
    NgxEchartsModule.forRoot({
      echarts: { init: echarts.init }
    }),
  ],
})
export class AppModule {}

原因是:使用的版本低于5.0

2.3.3.Cannot destructure property createHash

如果出现以下错误TypeError: Cannot destructure property 'createHash' of 'undefined' or 'null'

npm add webpack@latest

webpack版本原因,需要升级版本

2.3.4.Cannot destructure property compile

出现错误,TypeError: Cannot destructure property 'compile' of 'undefined' or 'null'.

npm install -D webpack-dev-server@3.0.0

问题:webpack-dev-server版本过高引起,重新安装3.0.0版本

2.3.其他组件中调用

2.3.1.HTML代码

<div echarts [options]="options" class="demo-chart" style="width: 100%; height: 560px;"></div>

2.3.2.TS代码

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.scss'],
})
export class TestComponent implements OnInit {
  options: any;
  constructor() {}

  ngOnInit(): void {
    const xAxisData = [];
    const data1 = [];
    const data2 = [];

    for (let i = 0; i < 100; i++) {
      xAxisData.push('category' + i);
      data1.push((Math.sin(i / 5) * (i / 5 - 10) + i / 6) * 5);
      data2.push((Math.cos(i / 5) * (i / 5 - 10) + i / 6) * 5);
    }

    this.options = {
      legend: {
        data: ['bar', 'bar2'],
        align: 'left',
      },
      tooltip: {},
      xAxis: {
        data: xAxisData,
        silent: false,
        splitLine: {
          show: false,
        },
      },
      yAxis: {},
      series: [
        {
          name: 'bar',
          type: 'bar',
          data: data1,
          animationDelay: (idx) => idx * 10,
        },
        {
          name: 'bar2',
          type: 'bar',
          data: data2,
          animationDelay: (idx) => idx * 10 + 100,
        },
      ],
      animationEasing: 'elasticOut',
      animationDelayUpdate: (idx) => idx * 5,
    };
  }
}

2.4.更新图表

在使用过程中,发现在初始化之后生成图表,无法进行更新修改,这个时候echart提供如下方案
HTML:

<div echarts [options]="chartOption" class="demo-chart" style="width: 100%; height: 560px;" (chartInit)="onChartInit($event)"></div>

TS:(调用echartsIntance即可)

chartOption:any; // 为已加载好的数据
echartsIntance: any;
onChartInit(ec: any) {
  this.echartsIntance = ec;
 }
  changeFunction() {
  	this.chartOption.xAxis.name='TEST1111';
  	 if(this.echartsIntance) this.echartsIntance.setOption(this.chartOption, true);
  }

问题:在初始化的时候,我们不要使用echartsIntance,因为这个时候echartsIntanceundefine,在初始化的时候,如果能获取到数据,那么直接在ngOnInit中对chartOption进行赋值。
具体使用请参考网站:W3Cschool

2.5.水平直线

在这里插入图片描述

let showOneData = [12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12];
let showOneName = 'p-1 (标准线:12)';
let option = {
	......
    series: [
        {
            name: showOneName,
            type: 'line',
            symbol: 'rect',
            smooth: 'true',
            symbolSize: 0,
            showSymbol: 'false',
            lineStyle: {
                normal: {
                    width: 2
                }
            },
            data: showOneData,
            color: '#2C4A5C'
        },
    ]
};

说明: 在legend中通过同一个类型,对line和bar同时进行控制

2.6.标准线

标准线上的颜色和下面的颜色进行区分

let option = {
   visualMap: {
        show: false,
        pieces: [// 进行颜色区分
          {
            gt: 0,// 大于0
            lte: 10,// 小于10
            color: '#ED002E'
        }, {
            gt: 10,// 大于10
            color: '#2C4A5C'
        }]
    },
    series: [{
        type: 'line',
        smooth:true, //平滑曲线
        data: [0, 4, 5, 9, 11, 15, 12, 8, 5, 3],
        markLine: {
            silent: true,
            lineStyle: {
              normal: {
                color: '#01fef9'// 设置标准线的颜色
              }
            },
            data: [{
                yAxis: // 定位标准线的横坐标位置
            }],
            label: {
              normal: {
                formatter: '标准线'
              }
            },
        },
    }]
};

2.7.柱状重叠图

在这里插入图片描述

let option1 = {
 	legend:{
 		data: ['Actual Assignment','Available Resource'],
 		align: 'left',
 		left:'6%',
 		itemGap: 50,
 		icon: 'circle',
 		textStyle:{
 			fontFamily: 'Arial',
           fontWeight: 400,
           fontStyle: 'normal',
           fontSize: 14,
           color: '#222B45',
		}
	},
	tooltip: {},
	xAxis: {
		name: '2020',
		data: ['2020-07-11','2020-07-12' ,'2020-07-13', '2020-07-14', '2020-07-15', '2020-07-16'],
		silent: false,
		splitLine: {
			show: false,
		},
		nameTextStyle: {
			fontWeight: '700',
			fontSize: 14,
			fontFamily:['Microsoft Tai Le Bold', 'Microsoft Tai Le Regular', 'Microsoft Tai Le']
		}
	},
	yAxis: {
		name: 'Hours',
		nameTextStyle: {
			fontWeight: '700',
			fontSize: 14,
			fontFamily:['Microsoft Tai Le Bold', 'Microsoft Tai Le Regular', 'Microsoft Tai Le']
		}
	},
	series:[{
		name: 'Actual Assignment',
		type: 'bar',
		data: [20, 30,40,30,25,55],
		animationDelay = (idx: number) => idx * 10,
		color:'rgba(24, 144, 255, 0.85)',
		barGap:'-100%',
		barWidth: '50%',
		z: 3
	},
	{
		name: 'Available Resource',
		type: 'bar',
		data: [60, 60,60,60,60,60],
		animationDelay = (idx: number) => idx * 10,
		color:'rgba(156, 202, 137, 1)',
		barGap: null,
		barWidth: '50%',
		z: null
	}],
	animationEasing = 'elasticOut',
	animationDelayUpdate =(idx) => idx * 5
}

3.ngx-translate

3.1.安装

3.1.1. 版本

版本1

  • Angular 版本: 8.3.26
  • ngx-translate/core 版本:11.0.1
  • ngx-translate/http-loader版本:4.0.0

3.1.2.命令

npm install @ngx-translate/core@11.0.1 --save
npm install @ngx-translate/http-loader@4.0.0 --save

安装好后,在package.json中会出现:

"dependencies": {
    "@ngx-translate/core": "^11.0.1",
    "@ngx-translate/http-loader": "^4.0.0"
  },

3.2.引入TranslateModule

app.module.ts中引入

import { TranslateModule, TranslateLoader } from '@ngx-translate/core';
import { TranslateHttpLoader } from '@ngx-translate/http-loader';
import {HttpClient, HttpClientModule} from '@angular/common/http';
export function createTranslateLoader(http: HttpClient) {
  return new TranslateHttpLoader(http, './assets/i18n/', '.json');
}

@NgModule({
	...
	imports: [
	...
    HttpClientModule,
    TranslateModule.forRoot({
      loader: {
          provide: TranslateLoader,
          useFactory: createTranslateLoader,
          deps: [HttpClient]
      }
    })
  ],
  ...
})

3.3.创建json语言包

在app.module.ts中, 就已经定义了translate的语言包的路径为./assets/i18n/,文件格式为json
所以创建一个zh.json的文件,内容如下:

{
	"test":"测试"
}

3.4.组件中使用

3.4.1.在app-root组件下引入(建议)

import { Component } from '@angular/core';
import {TranslateService} from '@ngx-translate/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})

export class AppComponent {
  constructor(public translate: TranslateService) {
    translate.setDefaultLang('zh');
    translate.use('zh');
  }
}

3.4.2.在ts中调用

ngOnInit中使用

import { TranslateService, TranslationChangeEvent } from '@ngx-translate/core';
export class TestComponent implements OnInit {
	test: string;
   	constructor(public translate: TranslateService) { }
  	ngOnInit() {
		this.translate.onLangChange.subscribe((event: TranslationChangeEvent) => {
		  test = this.translate.instant('test');
		});
	}
}

在其他方法中使用

let test = this.translate.instant('test');

3.4.3.在html中使用

<span>{{ 'test' | translate}}</span>

4.ngx-toastr

4.1.安装

npm install ngx-toastr --save

npm install ngx-toastr@10.1.0 --save //指定按本,注意angular版本和ngx-toastr版本的对应关系

如果没有安装animations,请先安装:

npm install @angular/animations --save

最后会在packing.json里面出现:"ngx-toastr": "^10.1.0",
注意:安装的版本和angular的版本的关系:

ngx-toastrAngular
6.5.04.x
8.10.25.x
10.1.08.x 7.x 6.x
11.3.38.x
12.1.09.x
current>= 10.x

由于我的angular版本时8.0的,因此引入的版本是10.1.0

4.2.引入

4.2.1.引入css

{
 "projects":{
 	...
 	"styles": [
	  "src/styles.scss",
	  "node_modules/ngx-toastr/toastr.css" //需要引入的
	],
 }

4.2.2.引入module

在api.module.ts中引入

import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import { ToastrModule } from 'ngx-toastr';
@NgModule({
	imports: [
		...
		BrowserAnimationsModule,
		ToastrModule.forRoot(
	      {
	        timeOut: 5000, //显示的时间
	        positionClass: 'toast-top-center', //位置toast-top-center、toast-top-right、inline、toast-bottom-right等
	        preventDuplicates: true, //是否阻止重复信息
	      }
	    ),
	    ...
	]
})

4.3.在组件或Service中使用

import { Injectable } from '@angular/core';
import { ToastrService } from 'ngx-toastr';

@Injectable()
export class TestService {
	constructor(private toastr: ToastrService){}
	showErrorMsg(title: any, msg: any){
	    this.toastr.error(msg, title, {closeButton: true});// 【错误】,closeButton:关闭按钮是否显示
	  }
	  showSuccessMsg(title: any, msg: any){
	    this.toastr.success(msg, title, {closeButton: true});// 【成功】
	  }
	  showWarningMsg(title: any, msg: any){
	    this.toastr.warning(msg, title, {closeButton: true});// 【警告】
	  }
	  showInfoMsg(title: any, msg: any){
	    this.toastr.info(msg, title, {closeButton: true});// 【提示】
	  }
}

5.ngx-clipboard复制到粘贴板

5.1.安装

npm install ngx-clipboard --save

5.2.组件引入

import { ClipboardModule } from 'ngx-clipboard';

imports: [
	...
    ClipboardModule,
    ...
]

5.3.HTML使用

5.3.1.复制输入框内容

<input type="text" [(ngModel)]="copyContent" placeholder="复制的内容">
<button [ngxClipboard]="copyContent">复制</button>

或者

<input type="text" #copyInput />
<button [ngxClipboard]="copyInput">复制</button>

5.3.2.复制自定义内容

<button ngxClipboard [cbContent]="'自定义复制的内容'">复制</button>

使用cbContent进行获取,如果是某个字符串,需要用引号引起来;但ngxClipboard为必选

5.3.3.调用回调函数

<button ngxClipboard [cbContent]="'自定义复制的内容'"
(cbOnSuccess)="successBackFunc($event)" 
(cbOnError)="errorBackFunc($event)">复制</button>

successBackFuncerrorBackFunc为成功和失败后的回调函数

6.ngx-quill富文本编辑器

6.1.安装和使用

6.1.1.安装

npm i ngx-quill
npm i quill

6.1.2.引入

6.1.2.1.引入模块
import { QuillModule } from 'ngx-quill';

imports: [
QuillModule.forRoot(),
...
]
6.1.2.2.引入样式

在angular.json文件的styles中加入

"styles": [
 "src/styles.scss",
  "./node_modules/quill/dist/quill.snow.css"
],

6.1.3.使用

<quill-editor ></quill-editor>

6.2.使用

6.2.1.使用在form表单

6.2.1.1. HTML文件
<form [formGroup]="editorForm">
                <quill-editor formControlName="editor" placeholder="内容" [styles]="{'min-height':'300px'}"></quill-editor>
                <button (click)="getContent()">获取内容</button>
</form>
6.2.1.2. ts文件
import { FormControl, FormGroup } from '@angular/forms';
export class TestComponent implements OnInit {
	editorForm: FormGroup;
	ngOnInit() {
	    this.editorForm = new FormGroup({
	      'editor': new FormControl(null);
	    });
    }
    getContent() {
		console.info(this.editorForm.value);
	}
}

6.2.2.单独使用(上传图片)

6.2.2.1.HTML
<quill-editor [(ngModel)]="content" placeholder="请输入内容" [styles]="{'min-height':'300px'}" (onEditorCreated)="editorCreated($event)" ></quill-editor>
<button (click)="getEditorContent()">获取内容</button>
6.2.2.2.ts文件

export class TestComponent implements OnInit {
	editor: any;
	
	constructor(private httpService: AppService) { }// AppService是专门用于请求数据的service
	editorCreated(quill) {
	  const toolbar = quill.getModule('toolbar');
	  toolbar.addHandler('image', this.imageHandler.bind(this));
	  this.editor = quill;
	}
	
	imageHandler() {
	  const Imageinput = document.createElement('input');
	  Imageinput.setAttribute('type', 'file');
	  Imageinput.setAttribute('accept','image/png, image/gif, image/jpeg, image/bmp, image/x-icon');
	  Imageinput.classList.add('ql-image');
	  Imageinput.addEventListener('change', () => {
	    const file = Imageinput.files[0];
	    const data: FormData = new FormData();
	    data.append('file', file, file.name);
	    const header = new Headers();
	    header.append('Accept', 'application/json');
	    if (Imageinput.files != null && Imageinput.files[0] != null) {
	      this.httpService.uploadImage('').subscribe(res => {
	        const range = this.editor.getSelection(true);
	        const index = range.index + range.length;
	        this.editor.insertEmbed(index, 'image', 'http://'+res['url']);
	      });
	    }
	  });
	  Imageinput.click();
	}
	
	getContent() {
		console.info(this.editorForm.value);
	}
}
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值