SwapnilM
SwapnilM

Reputation: 187

how to bind img src in angular 6 with TypeScript 4.1.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"              
],

Upvotes: 2

Views: 6743

Answers (2)

Barremian
Barremian

Reputation: 31125

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"/>

Upvotes: 6

RK001
RK001

Reputation: 171

This always works

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

Upvotes: 0

Related Questions