angular组件数据双向绑定
2019年3月4日
没有评论
周末的时候给网站做一个后台,前端用的是阿里的antd的angular版本。其中有用到他们的上传组件,由于有多个地方使用到上传,就把它封装成了一个通用图片上传组件。这时候服务端返回的图片链接地址,如何返回给父组件里面的表单里面哪?
通用上传组件
下面是我图片上传组件的实现:
image-upload/image-upload.component.html
<nz-upload class="avatar-uploader"
nzAction="{{serverUrl}}"
nzName="avatar"
nzListType="picture-card"
[nzShowUploadList]="false"
[nzHeaders]="headers"
[nzBeforeUpload]="beforeUpload"
(nzChange)="handleChange($event)">
<ng-container *ngIf="!previewUrl">
<div class="ant-upload-text">Upload</div>
</ng-container>
<img *ngIf="previewUrl" [src]="previewUrl" class="avatar">
</nz-upload>
image-upload/image-upload.component.ts
import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core';
import {BACKEND_BASE_HOST, UPLOAD_IMAGE_API} from '../../services/Apis.namespace';
import { NzMessageService, UploadFile } from 'ng-zorro-antd';
import {LocalStorageService} from '../../services/local-storage.service';
@Component({
selector: 'app-image-upload',
templateUrl: './image-upload.component.html',
styleUrls: ['./image-upload.component.css']
})
export class ImageUploadComponent implements OnInit {
@Input() uploadUrl: string;
@Output() uploadUrlChange = new EventEmitter();
previewUrl: string;
serverUrl: string;
loading: boolean;
headers: {};
constructor(private msg: NzMessageService,
private store: LocalStorageService) { }
ngOnInit() {
console.log(UPLOAD_IMAGE_API);
this.serverUrl = UPLOAD_IMAGE_API;
this.loading = false;
this.headers = {'Authorization': 'Bearer ' + this.store.get('user.token')};
this.previewUrl = this.uploadUrl;
}
beforeUpload() {
}
handleChange(info: { file: UploadFile }): void {
console.log('info: ' + info);
switch (info.file.status) {
case 'uploading':
this.loading = true;
break;
case 'done':
if (info.file.response.error === '200') {
this.previewUrl = BACKEND_BASE_HOST + info.file.response.data;
this.uploadUrlChange.emit(info.file.response.data);
}
this.loading = false;
break;
case 'error':
this.msg.error('Network error');
this.loading = false;
break;
}
}
}
这里贴了一下代码的实现,原理可以查看官方的相关文档。我写的时候也参考了《Angular:实现组件间双向数据绑定》。
近期评论