1

My Application is either active (true) or inactive (!actice). I want to change my image source for each state:

<img [src]="{'../../resources/images/pause.png':active, '../../resources/images/play.png':!active}"

(typical boolean ? valueA : valueB isn't correct)

The code is running but the images aren't found. Changing the path didn't help. Maybe you can...

UPDATE folder structure

app | +--components | | | +--header (html, ts,...) | +--resources | | | +--images (png)

1
  • Can you share the folder structure of your app, and the img path that your browser try to load ? BTW, you should export your logic into a component method for a better readability Commented Nov 30, 2016 at 16:00

1 Answer 1

5

Plunker Demo

Don't put the curly braces {} in the quotes "" and make sure the paths are correct. Eitherwise this is how you would do it.

@Component({
  selector: 'my-app',
  template: `
    <div>
        <h2>{{active ? "Front": "Back"}} of '18 Civic Type R</h2>
        <label> Toggle Front and Back View
            <input type="checkbox" name="checkbox" [(ngModel)]="active" />
        </label>
        <br/>
        <img [src]="active ? frontPath : backPath">
    </div>
  `,
})
export class App {
  active:boolean = false;

  frontPath:string = "http://www.topgear.com/sites/default/files/styles/fit_980x551/public/images/news-article/carousel/2016/09/a4705f0aaad0587c653b37b03409b0a0/78932_new_civic_type_r_prototype_breaks_cover_in_paris-1.jpg?itok=Few4WV6D";

  backPath:string = "http://tophondacars.com/wp-content/uploads/2018-Honda-Civic-Type-R-pwe.jpg";

  constructor() {

  }
}

OR

You could use *ngIf and just show/hide (add/remove technically) when you want to.

*ngIf

Removes or recreates a portion of the DOM tree based on an {expression}.

If the expression assigned to ngIf evaluates to a falsy value then the element is removed from the DOM, otherwise a clone of the element is reinserted into the DOM.

<img *ngIf="active" [src]="../../resources/images/pause.png">
<img *ngIf="!active" [src]="../../resources/images/play.png">
Sign up to request clarification or add additional context in comments.

2 Comments

Good! Glad to help out!

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.