What's Better To Use In Angular - Src Or [src]
<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.
Solution 2:
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:
<imgsrc="{{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"/>
Solution 3:
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';
Post a Comment for "What's Better To Use In Angular - Src Or [src]"