【问题标题】:Hide other elements in list隐藏列表中的其他元素
【发布时间】:2019-04-08 12:47:49
【问题描述】:

我有以下代码:

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

代码位于for 循环中。当我点击一个标签时,所有标签都应该被隐藏并且输入应该是可见的。目前,当我点击每个标签时,另一个保持打开状态。单击任何项​​目时如何隐藏另一个跨度?

我在 .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();
  }

如何解决?

【问题讨论】:

  • 你能用ngFor发布你的完整html吗?
  • 用 for 更新了 html
  • 你试过这个吗:@ViewChildren('tagInput') tagNameTextInput: QueryList&lt;ElementRef&gt; 而不是@ViewChild('tagInput') tagNameTextInput: ElementRef;。因为在你的 for 循环元素中 ref 并不保持唯一。
  • 你能创建工作演示吗?您应该使用NgIf 隐藏元素,但尚不清楚您是否可以访问此侦听器中的其他数组元素
  • @Md.ParvezAlam,也可以试试@ViewChildren 代替@ViewChild。因为你有多个孩子。我已经更新了我的评论。

标签: javascript angular angular6 viewchild


【解决方案1】:

最好的方法是为“项目”添加一个新属性,(例如,称为“编辑”)所以

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

看几件事:

1.-点击标签,变量变为真,所以显示输入

2.-在item的模糊中,变量变为false,所以标签显示出来

3.-使用[(ngModel)]来表示输入和值的关系

【讨论】:

    【解决方案2】:

    您有多个孩子,因此您需要使用@ViewChildren 而不是@ViewChild。

    同样在您的ngFor 循环中,您没有唯一的模板引用#tagInput。将QueryList 与ElementRef 一起使用。

    试试看:@ViewChildren('tagInput') tagNameTextInput: QueryList&lt;ElementRef&gt;;

    而不是

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

    从@angular/core 导入查询列表。

    赞这个import { Component, QueryList } from '@angular/core';

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-08-19
      • 2020-10-12
      • 1970-01-01
      • 1970-01-01
      • 2018-11-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多