Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Whats equivalent to ngSrc in the newer Angular?

Tags:

angular

I would like to implement img, with a src coming from JSON object.

In AngularJS, I could do:

<img ng-src="{{hash}}" alt="Description" /> 

Is there any equivalent to this in Angular 2+?

like image 458
uksz Avatar asked Jun 22 '16 10:06

uksz


2 Answers

AngularJS:

<img ng-src="{{movie.imageurl}}"> 

Angular 2+:

<img [src]="movie.imageurl"> 

Angular docs


Note that interpolation can achieve the same result:

<img src="{{vehicle.imageUrl}}">  <img [src]="vehicle.imageUrl"> 

There is no technical difference between these two statements for property binding, as long as you don't desire two-way binding.

Interpolation is a convenient alternative for property binding in many cases. In fact, Angular translates those interpolations into the corresponding property bindings before rendering the view. source

like image 151
Randy Avatar answered Oct 17 '22 07:10

Randy


It is a two-step process to achieve the same functionality of ng-src in your Angular application.

First Step:

In your HTML, use the new syntax:

<img [src]="imageSrc">

Second Step:

In your component/directive, initialize the value to be empty. For example:

@Component({   selector: 'ag-video',   templateUrl: './video.component.html' }) export class SampleComponent {    imageSrc = ''; } 

Now, this would eliminate the null network call (empty call) due to the value not being set on to the element.

like image 39
Nikhilesh Shivarathri Avatar answered Oct 17 '22 08:10

Nikhilesh Shivarathri