Hide other elements in list

最后都变了- 提交于 2019-12-11 06:48:19

问题


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?


回答1:


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';




回答2:


the best aproach is add a new property to "item", (e.g. called "editing") so

<li *ngFor="let item of Array let i = index">
  <span>
    <label *ngIf="!item.editing" (dblclick)="item.editing=true;">
      {{item.tag}}
    </label>
    <input *ngIf="item.editing" [(ngModel)]="item.tag" type="text" (blur)="item.editing=false"  />
  </span>
</li>

See several things:

1.-in a click of label, the variable becomes true, so the inpùt is showed

2.-in blur of item, the variable becomes false, so the label is showed

3.-Use [(ngModel)] to relation between the input and the value



来源:https://stackoverflow.com/questions/53149659/hide-other-elements-in-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!