2

I am using Angular6 and typeScript4.1.2 and trying to load image from app.component.ts and binding it in app.component.html but image is not showing up. The strange thing is when I am trying to load it directly in app.component.html the image is visible. Please help me to understand what I am missing in app.component.ts

app.component.ts :

declare function require(path:string):string;
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})

export class AppComponent {
  title = 'angular-ui';
  imagesrc = require('../assets/images/myimage.png');
}

app.component.html :

<nav class="navbar navbar-expand-lg navbar-light bg-light">
  <div class="container-fluid">
    <div class="navbar-header">
      <a class="navbar-brand" href="#">        
        <img src={{imagesrc}} height="26"/>
        <!-- <img src="../assets/images/myimage.png" height="26"/> -->
      </a>
      Test
    </div>
  </div>
</nav>

I have tried almost all the combination to access the myimage.png in app.component.ts but none of these worked

imagesrc = require('../assets/images/myimage.png');
imagesrc = require('/assets/images/myimage.png');
imagesrc = require('assets/images/myimage.png');

I have tried to use autocomplete as well but Visual studio code not showing any suggestion after ../assets/images/

And assets path is already set in Angular.json

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

2 Answers 2

6

I don't think you need the require call. Try to bind the path directly

Controller

export class AppComponent {
  title = 'angular-ui';
  imagesrc = '../assets/images/myimage.png';
}

Template

<img [src]="imagesrc" height="26"/>
Sign up to request clarification or add additional context in comments.

Comments

0

This always works

<img [src]="imagesrc" height="26"/>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.