Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 5 add baseURI to image src and can't dynamically load image

I work on angular 5.2.1 and I want to load an image whose src comes from a server

HTML

<img #image [src]="cover" class="img-fluid" alt="NO image">

image-loader.component.ts

     import { Component, OnInit, Input, AfterViewInit,ViewChild,ElementRef} from '@angular/core';
    import { EventAccessService } from '../../../event/services/event-acces.service';

    @Component({
      selector: 'loader',
      templateUrl: './loader.component.html',
      styleUrls: ['./loader.component.scss']
    })
    export class EventCardComponent implements OnInit, AfterViewInit {
      @Input('cover') cover: any;

    @ViewChild("image", {read: ElementRef}) image: ElementRef;

      constructor(private service: EventAccessService) {

      }
    ngOnInit() {}
     ngAfterViewInit() {

        console.log(this.image.nativeElement.currentSrc);
        this.image.nativeElement.src=this.cover
        console.log(this.image.nativeElement.src);
    }
}

Result from chrome console : http://localhost:4200/(which is the baseURI) concatenated to the variable cover(which is the full link to the image)

As a result the image doesn't load

Help Please!!

EDIT

I changed the image.nativeElement.src to cover directly at the ngAfterViewInit but still no change

like image 875
Philippe Steve Avatar asked Feb 24 '26 22:02

Philippe Steve


1 Answers

Here I have used RxjS like so: i.e. you can put the image URL where it is coming from the server into BehaviorSubject like below.

.html

<img [src]="photoHandlerService?.userProfilePhotoChanged$ | async" #userProfilePhoto>

.ts

 @ViewChild('userProfilePhoto') userProfilePhoto: ElementRef;

 constructor(public photoHandlerService: PhotoHandlerService) { }

  ngAfterViewInit(): void {
    console.log(this.userProfilePhoto.nativeElement.src);
  }

service.ts

 private profilePhoto: string = 'assets/images/jpgs/profilePhoto.jpg';
 private userProfilePhotoSubject$: BehaviorSubject<string> = new BehaviorSubject<string>(this.profilePhoto);
 userProfilePhotoChanged$: Observable<string> = this.userProfilePhotoSubject$.asObservable();

 constructor()

setUserProfilePhoto(photoUrl: string): void {
    this.userProfilePhotoSubject$.next(photoUrl);
}
like image 83
Sampath Avatar answered Feb 26 '26 13:02

Sampath



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!