nCore nCore - 1 month ago 23
Javascript Question

Angular 2 hide textarea which the user unchecked

How can I hide a

textarea
when I unchecked a
checkbox
when the
textarea
is being rendered in
*ngFor
? So the checkbox should be bind with the textarea, right? It should only hide the
textarea
which the user unchecked and the others should stay visible.

I've been trying to figure out the easiest way of doing it though in my actual code its returning me
true
if the boxed is ticked and
false
if it's not, however it not hiding the
textarea
at all. The default value is true so it shows all the textarea as default.

For some reason this plnkr doesn't allow me use
[(ngMode)]
I think its a different RC of angular, but the example below is basically the problem I have when you uncheck the box it doesn't hide the textarea.

http://plnkr.co/edit/tOdtcmWxFB6vGuLyCqZS?p=preview

My original code:

<label for="inputSearch.name" style="float: left;">
<input type="checkbox" id="{{inputSearch.name}}" [checked]="chkProp" (click)="chkboxCookie()" [(ngModel)]="inputSearch.value"> {{inputSearch.name}}
</label>

<div class="" *ngFor="let inputSearch of searchBoxCount" class="col-sm-12">
<textarea name="{{inputSearch.name}}" id="{{inputSearch.name}}" rows="3" class="search-area-txt" attr.placeholder="Search {{inputSearch.name}}" [(ngModel)]="inputSearch.value" *ngIf="chkProp || chkProp==true || inputSearch.name"></textarea>
<p> {{inputSearch.name}} - {{inputSearch.value}}</p>
</div>

Answer

Solved

Use an array of checkedUsers, and set the checkbox to checked if the user ISN'T found in the array. Then, hide the textarea if the user IS found in the array.

THEN, on the checkboxes change pass the user to the change and add the user if they aren't in the array of checkedUsers and if they already are in it then remove them.

PLUNKER

Here is what your component should look like

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
    styles: [`
    .hidden {
      display: none;
    }
    `],
  template: `<p *ngFor="let user of users">{{ user.name }} - {{ user.age }} </p>

   <div *ngFor="let user of users">
      <textarea name="{{user.name}}" id="{{ user.name }}" [class.hidden]="checkedUsers.indexOf(user) >= 0"></textarea>
      <input type="checkbox" id="{{ user.name }}" [checked]="checkedUsers.indexOf(user) < 0" (click)="change(user)"/>
      <p>{{user.name}}</p>
   </div>

  `
})
export class AppComponent { 
  public users: string;
  public checkedUsers = [];
  change(user): void {
    var indexOfItem = this.checkedUsers.indexOf(user);
    if(indexOfItem >= 0) {
      this.checkedUsers.splice(indexOfItem, 1);
    } else {
      this.checkedUsers.push(user);
    }

  }
  constructor() {
    this.users = [{name: 'User1', age: '21'}, {name:'User2', age:'31'}];

  }
}
Comments