In Angular 8 I have 2 components: add-book & display-book ad inject service - book.service. I search problem with preview image from display-book.component.ts. When it's save in books array, display-book component display image from this array. Apart image, title and description is display, work fine. I was looking for using FileReader but without any effects.
book.service.ts:
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class BookService {
constructor() { }
url: any = '';
books: any[] = [];
addBook(imageUrl: string, title: string, description: string) {
const imgUrl: string = imageUrl
const book = {
imgUrl,
title,
description
}
this.books.push(book);
console.log(this.books);
}
}
display-book.component.ts:
import { BookService } from './../services/book.service';
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-display-book',
templateUrl: './display-book.component.html',
styleUrls: ['./display-book.component.scss']
})
export class DisplayBookComponent implements OnInit {
url = this.bookService.url;
books = this.bookService.books;
constructor(private bookService: BookService) { }
ngOnInit() { }
displayBooks(event) {
console.log(this.books)
if (event.target.files && event.target.files[0]) {
var reader = new FileReader();
reader.onload = (event:any) => {
this.url = event.target.result;
}
reader.readAsDataURL(event.target.files[0]);
}
}
}
add-book.component.ts:
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder } from '@angular/forms';
import { BookService } from '../services/book.service';
@Component({
selector: 'app-add-book',
templateUrl: './add-book.component.html',
styleUrls: ['./add-book.component.scss']
})
export class AddBookComponent implements OnInit {
addForm: FormGroup;
constructor(private formBuilder: FormBuilder, private bookService: BookService) { }
ngOnInit() {
}
createForm() {
this.addForm = this.formBuilder.group({
BookImageUrl: [''],
BookTitle: [''],
BookDescription: ['']
});
console.log(this.addForm);
}
addBook(imageUrl: HTMLInputElement, title: HTMLInputElement, description: HTMLInputElement) {
this.bookService.addBook(imageUrl.value, title.value, description.value);
}
}
imgtag. Something like this:<img [src]="imgUrl" />?