0

I am learning Angular 4. I want to show an image when the checkbox is checked. But its not working. My app.component.html looks like this:

<input type="checkbox" name="chec" [(ngModel)]="check1" value="http://www.clipart-library.com/data_images/432133.jpg">

<img src="{{check1}}" height="100" width="100">

3 Answers 3

1

One thing till I will answer your question. Two-way data binding is bad pattern and You shouldn't use it, even Angular creators stopped to improve it since Angular 2.

I recommend using here something called *ngIf - this is angular conditional instruction which allows you to check conditions in HTML.

 <input type="checkbox" name="chec" [(ngModel)]="check1">
 <div *ngIf="check1">
     You will see this only when checkbox is checked!
 </div>

Addiotional - do not bind file path to ngModel.As @Rakesh said it's logical value. What is more even object 2-way binded with path value, will constantly check for file path changes and it would probably slow down your application.

Sign up to request clarification or add additional context in comments.

Comments

1

.HTML

<input type="checkbox" name="chec" (change)="checkOnClick($event)" value="http://www.clipart-library.com/data_images/432133.jpg">
  <img src="{{check2}}" height="100" width="100">

.TS

export class App {
  check2:string = "";
  constructor() {

  }
  checkOnClick(e:any){
    if(e.target.checked){      
      this.check2 = e.target.value;
   }
  }
}

Plunker URL : https://plnkr.co/edit/S6f01oy0YQ8e94mQg7Uv?p=preview

Comments

1

Value will not be work when you are using [(ngModel)]="check1" this is only show true or false. If you want to show image on checked then you can change your code like this

<img src="{{check1 ? 'url of image when checked': 'do what ever you want if not checked'}}" height="100" width="100">

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.