Build Your First Angular Website

Adding an Image/Logo in Angular

We currently have the default Bulma logo in our header. It's also an image link that points to a separate domain (https://bulma.io/images/bulma-logo.png). This won't be good long term because if Bulma ever decided to change that URL, then our app's logo would stop working.

It's also a better idea to store this within our project folder so that all assets are served from our same domain. Less round trips means better performance (and Google PageSpeed score).

How the Angular CLI Deals with Images

Remember when we used the npm run build or ng build --prod command? Angular CLI moved all of our assets into the dist folder. It will do the same when it sees that there are images inside the assets folder.

All we have to do is reference these images in our templates with a path that starts inside the src folder.

For instance, if we have an image at src/assets/img/logo.png, we would add this to our template:

template: `
  <img src="assets/img/logo.png">
`

Adding An Image to the Assets Folder

The assets folder that the Angular CLI generated for us is the perfect place to use for storing images.

Let's go grab the Angular logo from angular.io.

https://angular.io/assets/images/logos/angular/logo-nav@2x.png

Go ahead and save that to our assets folder inside of an img folder. I've named mine angular-logo.png:

Using the Image In Our Template

Now we can reference this image in our header.component.ts

@Component({
  selector: 'app-header',
  template: `
    <nav class="navbar">

      <!-- logo -->
      <div class="navbar-brand">
        <a class="navbar-item">
          <img src="assets/img/angular-logo.png">
        </a>
      </div>
    </nav>
  `,
  styles: []
})

Let's also change the color of our header to be a darker color. We'll just add the is-dark class to the <nav>:

<nav class="navbar is-dark">

You can see the other colors on the Bulma docs and select whichever you like!

  • is-primary
  • is-link
  • is-info
  • is-success
  • is-warning
  • is-danger
  • is-black
  • is-dark
  • is-light
  • is-white

Angular CLI Moves Images to dist on build

Let's try building this application now and seeing what the Angular CLI does.

npm run build

Our entire assets folder has been moved over to the dist folder now! The path will also work since we referenced it from within the src folder. Now it's just referencing from within the dist folder.