Search code examples
javascriptangularangular6viewchild

Hide other elements in list


I have the below code:

<li *ngFor="let item of Array let i = index">
  <span>
    <label (dblclick)="editTag($event,i)">
      {{item.tag}}
    </label>
    <input type="text" #tagInput  />
  </span>
</li>

The code is in a for loop. When I click on a label, all labels should be hidden and the input should be visible. Currently, when I click on each label, the other remain open. How do I hide the other span when clicking on any item?

I have below code in .ts

@ViewChild('tagInput') tagNameTextInput: ElementRef;
  editTag(event: any,index: any) {
    //console.info(event);
    this.tagNameTextInput.nativeElement.hidden = true;
    this.tagNameTextInput.nativeElement.previousElementSibling.hidden = false;
    let initialValue = event.target.childNodes[0].nodeValue.trim();
    event.target.hidden = true;
    event.target.nextElementSibling.hidden = false;
    event.target.nextElementSibling.value = initialValue;
    console.log(index);
    // this.checkListNameHidden = true;
    // this.checkListNameTextInput.nativeElement.value = initialValue;
    // this.checkListNameTextInput.nativeElement.focus();


    event.stopPropagation();
  }

How to solve this?


Solution

  • You have multiple children, So you need to use @ViewChildren instead of @ViewChild.

    Also in your ngFor loop you do not have unique template reference #tagInput. Use QueryList with ElementRef.

    Try : @ViewChildren('tagInput') tagNameTextInput: QueryList<ElementRef>;

    instead of

    @ViewChild('tagInput') tagNameTextInput: ElementRef;.

    Import QueryList from @angular/core.

    Like this import { Component, QueryList } from '@angular/core';