Angular 2在点击关闭按钮时隐藏父元素

Angular 2在点击关闭按钮时隐藏父元素

问题描述:

我是Angular2中的新成员,我想在点击关闭图标后隐藏父元素。以下是我的代码:Angular 2在点击关闭按钮时隐藏父元素

@Component({ 
    selector: 'add-search', 
    template: ` 
     <input type='text' #newHero 
     (keyup.enter)="addHero(newHero.value)" 
     (blur)="addHero(newHero.value); newHero.value='' "> 
     <button (click)=addHero(newHero.value)>Add</button> 
    <div> 
    <div [hidden]="hideElement" style="margin-right:2px" *ngFor="let hero of heroes" class="label label-primary">{{hero}}<span (click)="toggleElement()" style='cursor:pointer; display:inline-block; padding:1px 2px;'><i class="fa fa-times" aria-hidden="true" style="font-size:10px;"></i></span> 
</div> 
</div> 
    ` 
}) 
export class AddSearchComponent { 
    heroes = Array<string>(); 
    addHero(newHero: string) { 
     if (newHero) { 
      this.heroes.push(newHero); 
     } 
    } 
    private hideElement: boolean = false; 
    toggleElement() { 
     if (this.hideElement) { 
      this.hideElement = false; 
     else 
      this.hideElement = true; 
    } 
} 
} 

隐藏不在代码中工作。我们能以简单的方式做到吗?或者什么是最好的方法?

<div [hidden]="hero.hideElement" style="margin-right:2px" 
    *ngFor="let hero of heroes" 
     class="label label-primary">{{hero}} 

     <span (click)="hero.hideElement=!hero.hideElement" 
       style='cursor:pointer; display:inline-block; padding:1px 2px;'> 
       <i class="fa fa-times" aria-hidden="true" style="font-size:10px;"></i> 
     </span> 
</div> 

// toggle is not possible. 

OR

<span *ngFor="let hero of heroes" 
     (click)="hero.hideElement=!hero.hideElement" 
     style='cursor:pointer; display:inline-block; padding:1px 2px;'> 
     <i class="fa fa-times" aria-hidden="true" style="font-size:10px;"></i> 

    <div [hidden]="hero.hideElement" style="margin-right:2px"   
      class="label label-primary"> 
      {{hero}}  
    </div> 
</span> 

// toggle is possible. 

更新

你是否在使用阵列Array对象的不明确。 SO我给你数组对象

随着字符串数组的解决方案,它是不可能隐藏与* ngFor回路的元件。你所能做的只是拼接

在这里检查两种方式。

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

+0

感谢@micronyks。实际上,如果需要,我想在删除文本后将其添加到页面上。我只是试图使用切换。不幸的是,对我而言,它不像我上面所说的那样工作。 – Sunil

+0

所以你可以按照第一个建议。它会工作。您不需要ts文件中的点击事件功能。你可以从hTML本身处理它,如图所示。 – micronyks

+0

单击两个建议中的关闭图标后,我无法关闭。 – Sunil