user7209780
user7209780

Reputation:

What's better to use in Angular - src or [src]

Just want to ask what is recommended to use with Angular, standard html src or Angular [src]? And why?

Edit: I have following code in my html component:

<img class="logo" src="../app/media/appLogo.png">

It is fine? If not, how should I change it to work together with [src]?

Edit2: Is there any other, better way to do it, instead of plain html src? Or this is the best solution actually?

Upvotes: 11

Views: 7186

Answers (3)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657376

[...]="..." is for object binding ...="{{...}}" is for binding with string interpolation. If you want to bind a string it doesn't matter what you use. If you want to bind an object or array value you need to use `[...]="...". Besides that it's entirely up to you.

<img class="logo" src="../app/media/appLogo.png">

Is not related to Angular2 at all, thats just plain HTML (no [] and no {{}}). If you add [] around src, then Angular will treat ../app/media/appLogo.png as an expression, which it clearly isn't.

When DomSanitizer is used [src]="..." is mandatory because the value no longer is a string, but an object and using {{}} would stringify it in an invalid way.

Upvotes: 9

Aniket
Aniket

Reputation: 582

If you have static anchor link, then go ahead with

<img class="logo" src="../app/media/appLogo.png">

When binding from the component, then either of the below will work.

<img class="logo" [src]="image_src">
<img class="logo" src="{{ image_src }}">

In component.ts

image_src: string = '../app/media/appLogo.png';

Upvotes: 1

Robba
Robba

Reputation: 8324

Using regular src sets the Attribute where setting [src] sets the property. Considering that for an image (I assume you're talking about an image but you don't say) the src attribute is used to set the corresponding property they will both work.

There is one big reason to use [src] though. Browsers tend to start downloading whatever you put in the src attribute while parsing the html. So lets say you do this:

<img src="{{myImgSrc}}"/>

The browsers will often immediately start downloading {{myImgSrc}}, which will lead to a 404 in the console. Using the following is therefor slightly better:

<img [src]="myImgSrc"/>

Upvotes: 5

Related Questions