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

前端 未结 3 1157
自闭症患者
自闭症患者 2020-12-20 18:17

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

Edit: I have follow

相关标签:
3条回答
  • 2020-12-20 18:23

    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"/>
    
    0 讨论(0)
  • 2020-12-20 18:26

    [...]="..." 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.

    0 讨论(0)
  • 2020-12-20 18:28

    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';
    
    0 讨论(0)
提交回复
热议问题