Angular 4 img src is not found

后端 未结 16 1499
我寻月下人不归
我寻月下人不归 2020-12-24 10:11

I\'m having a problem with sourcing an image with angular 4. It keeps telling me that the image is not found.

Folder structure:

app_folder/
app_compo         


        
相关标签:
16条回答
  • 2020-12-24 10:51

    Angular 4 to 8

    Either works

    <img [src]="imageSrc" [alt]="imageAlt" />
    
    <img src="{{imageSrc}}" alt="{{imageAlt}}" />
    

    and the Component would be

    export class sample Component implements OnInit {
       imageSrc = 'assets/images/iphone.png'  
       imageAlt = 'iPhone'
    

    Tree structure:

    -> src 
       -> app
       -> assets
          -> images
               'iphone.png'
    
    0 讨论(0)
  • 2020-12-24 10:54

    You must use this code in angular to add the image path. if your images are under assets folder then.

    <img src="../assets/images/logo.png" id="banner-logo" alt="Landing Page"/>
    

    if not under the assets folder then you can use this code.

    <img src="../images/logo.png" id="banner-logo" alt="Landing Page"/>
    
    0 讨论(0)
  • 2020-12-24 10:54

    Add in angular.json

      "assets": [
                  "src/favicon.ico",
                  "src/assets"
                ],
    

    And then use it like this: <img src={{imgPath}} alt="img"></div>

    And in ts: storyPath = 'assets/images/myImg.png';

    0 讨论(0)
  • 2020-12-24 10:55

    Check in your.angular-cli.json under app -> assets:[] if you have included assets folder.

    Or perhaps something here: https://github.com/angular/angular-cli/issues/2231, can help.

    0 讨论(0)
  • 2020-12-24 10:58
    <img src="images/no-record-found.png" width="50%" height="50%"/>
    

    Your images folder and your index.html should be in same directory(follow following dir structure). it will even work after build

    Directory Structure

    -src
        |-images
        |-index.html
        |-app 
    
    0 讨论(0)
  • 2020-12-24 10:58

    An important observation on how Angular 2, 2+ attribute bindings work.

    The issue with [src]="imagePath" not working while the following do:

    • <img src="img/myimage.png">
    • <img src={{imagePath}}>

    Is due your binding declaration, [src]="imagePath" is directly binded to Component's this.imagePath or if it's part of an ngFor loop, then *each.imagePath.

    However, on the other two working options, you're either binding a string on HTML or allowing HTML to be binded to a variable that's yet to be defined.

    HTML will not throw any error if you bind <img src=garbage*Th_i$.ngs>, however Angular will.

    My recommendation is to use an inline-if in case the variable might not be defined, such as <img [src]="!!imagePath ? imagePath : 'urlString'">, which can be though of as node.src = imagePath ? imagePath : 'something'.

    Avoid binding to possible missing variables or make good use of *ngIf in that element.

    0 讨论(0)
提交回复
热议问题