3

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

2
  • Setting the src attribute on the child element is not what you want to do. Just set cover once you know the URL. Commented Apr 5, 2018 at 2:59
  • I got the answer myself....my REST api was giving me the url in the form www.xxxx and angular was completing them (I don't really know why) so I added http:// infront of the url and all went ok...thanks everyone Commented Apr 5, 2018 at 15:23

1 Answer 1

1

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);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.