nCore nCore - 11 months ago 107
Javascript Question

Angular 2 hide textarea which the user unchecked

How can I hide a

when I unchecked a
when the
is being rendered in
? So the checkbox should be bind with the textarea, right? It should only hide the
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
if the boxed is ticked and
if it's not, however it not hiding the
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
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.

My original code:

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

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

Answer Source


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.


Here is what your component should look like

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

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

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

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 {

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