У меня есть дополнительный модальный компонент для добавления дома. Когда я нажимаю добавить дом, я получаю модальную форму для заполнения, и для этого есть кнопка загрузки файла.
У меня есть компонент загрузки, где я могу выбрать несколько файлов и загрузить его.
Чем я должен заполнить другую информацию и нажмите кнопку Добавить, чтобы добавить дом.
Но я хочу выбирать файлы, не загружая их напрямую, а загружать их только тогда, когда нажимаю кнопку добавления дома.
UploadComponent.ts
import { Component, OnInit, EventEmitter, Output } from '@angular/core';
import { HttpEventType, HttpClient } from '@angular/common/http';
@Component({
selector: 'app-upload',
templateUrl: './upload.component.html',
styleUrls: ['./upload.component.scss']
})
export class UploadComponent implements OnInit {
public imagePath;
imgURL: any;
public progress: number;
public message: string;
public files = []; @Output() public onUploadFinished = new EventEmitter();
constructor(private http: HttpClient) { }
ngOnInit() {
}
public uploadFile = (files: File[]) => {
if (files.length === 0) {
return;
}
const formData = new FormData();
for (let i = 0; i < files.length; i++) {
const fileToUpload = files[i];
formData.append('file', fileToUpload, fileToUpload.name);
}
this.http.post('https://localhost:5001/api/upload', formData, {reportProgress: true, observe: 'events'})
.subscribe(event => {
if (event.type === HttpEventType.UploadProgress) {
this.progress = Math.round(100 * event.loaded / event.total);
} else if (event.type === HttpEventType.Response) {
this.message = 'Upload success.';
this.onUploadFinished.emit(event.body);
}
});
// Preview image before upload
const reader = new FileReader();
this.imagePath = files;
reader.readAsDataURL(files[0]);
reader.onload = (_event) => {
this.imgURL = reader.result;
};
}
}
UploadComponent.html
<div class="row" style="margin-bottom:15px;">
<div class="col-md-3">
<img [src]="imgURL" height="200" *ngIf="imgURL">
<input type="file" #file placeholder="Choose file" multiple (change)="uploadFile(file.files)" style="display:none;">
<button type="button" class="btn btn-success" (click)="file.click()" >Upload File</button>
</div>
<div class="col-md-4">
</div>
</div>
AddModalComponent.ts
import { Component, OnInit, ViewChild, TemplateRef } from '@angular/core';
import { FormControl, FormGroup, Validators, FormBuilder } from '@angular/forms';
import { BsModalService } from 'ngx-bootstrap';
import { HouseService } from 'app/services/house.service';
import { HttpEventType, HttpClient } from '@angular/common/http';
import { ModalService } from 'app/services/modal.service';
import { FormControlsService } from 'app/services/form-controls.service';
@Component({
selector: 'app-add-modal',
templateUrl: './add-modal.component.html',
styleUrls: ['./add-modal.component.css']
})
export class AddModalComponent implements OnInit {
public response: {dbPath: ''};
// Add Modal
@ViewChild('template') modal: TemplateRef<any>;
constructor(
public modalProp: ModalService,
private modalService: BsModalService,
private houseService: HouseService,
private fb: FormBuilder,
public fc: FormControlsService
) { }
ngOnInit() {
const validateImageUrl = '^(https?:\/\/.*\.(?:png|jpg))$';
this.fc.name = new FormControl('', [Validators.required, Validators.maxLength(50)]);
this.fc.price = new FormControl('', [Validators.required, Validators.min(0), Validators.max(10000)]);
this.fc.description = new FormControl('', [Validators.required, Validators.maxLength(150)]);
this.fc.imageUrl = new FormControl('', []);
this.fc.insertForm = this.fb.group({
name : this.fc.name,
price : this.fc.price,
description : this.fc.description,
imageUrl : this.fc.imageUrl,
avalaible : true,
});
}
onAddHouse() {
this.modalProp.modalRef = this.modalService.show(this.modal);
}
public uploadFinished = (event) => {
this.response = event;
this.fc.imageUrl.setValue(this.response.dbPath);
}
// Method to Add new Product
onSubmit() {
const newProduct = this.fc.insertForm.value;
this.houseService.insertHouse(newProduct).subscribe(
result => {
this.houseService.clearCache();
this.modalProp.houses$ = this.houseService.getHouses();
this.modalProp.houses$ .subscribe(newlist => {
this.modalProp.houses = newlist;
this.modalProp.modalRef.hide();
this.fc.insertForm.reset();
// this.rerender();
});
console.log('New Product added');
},
error => console.log('Could not add Product')
);
}
}
AddModalComponent.html
<!-- ADD HOUSE MODAL START-->
<button class="btn btn-warning mb-3 float-right text-uppercase" *ngIf="modalProp.userRoleStatus == 'Admin'" (click)="onAddHouse()" ><i class="fa fa-plus"></i> Huis toevoegen</button><br>
<ng-template #template>
<div class="modal-header">
<h4 class="modal-title">ADD NEW HOUSE</h4>
<button type="button" class="close pull-right" aria-label="Close" (click)="modalProp.modalRef.hide()">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body text-center">
<p class="list-group-item active text-center text-uppercase"></p>
<form [formGroup]="fc.insertForm" (ngSubmit)="onSubmit()">
<ul class="list-group">
<li class="list-group-item">
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text" id="houseTitle"><i class="fa fa-pencil-square-o"></i></span>
</div>
<input type="text" id="name" formControlName="name" class="form-control" placeholder="Stad" aria-label="name" aria-describedby="houseTitle">
</div>
<div *ngIf="fc.name.touched && fc.name.errors" class="errorMessage" >
<span *ngIf="fc.name.hasError('required')">City Name is required.</span>
<span *ngIf="fc.name.hasError('maxlength')">Only 50 characters allowed for House Name.</span>
</div>
</li>
<li class="list-group-item">
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text" id="houseDescription"><i class="fa fa-pencil-square-o"></i></span>
</div>
<textarea formControlName="description" class="form-control" placeholder="Beschrijf het huis - Max 150 Tekens" aria-label="Description" aria-describedby="houseDescription"></textarea>
</div>
<div class="errorMessage" *ngIf="fc.description.touched && fc.description.errors">
<span *ngIf="fc.description.hasError('required')">House Description is required.</span>
<span *ngIf="fc.description.hasError('maxlength')">Only 150 characters allowed for House Description.</span>
</div>
</li>
<!-- <li class="list-group-item">
<div class="input-group">
<div class="input-group-prepend">
<div class="input-group-text">
<input type="checkbox" formControlName="available" checked aria-label="Checkbox for following text input">
</div>
</div>
<input type="text" class="form-control" placeholder="House available" disabled>
</div>
</li> -->
<li class="list-group-item">
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fa fa-usd"></i></span>
</div>
<input formControlName="price" type="text" class="form-control" placeholder="Prijs">
</div>
<div class="errorMessage" *ngIf="fc.price.touched && fc.price.errors">
<span *ngIf="fc.price.hasError('required')">House Price is required.</span>
<span *ngIf="fc.price.hasError('min')" >Negative price Not allowed</span>
<span *ngIf="fc.price.hasError('max')">Max price allowes is 10000</span>
</div>
</li>
<li class="list-group-item">
<app-upload (onUploadFinished)="uploadFinished($event)"></app-upload>
</li>
<li class="list-group-item">
<button [disabled]="fc.insertForm.invalid" class="btn btn-primary btn-block">ADD</button>
</li>
</ul>
</form>
</div>
</ng-template>
<!-- ADD HOUSE MODAL START-->