2016-09-23 10 views
1

私はAngular2で新しく、閉じるアイコンをクリックした後に親要素を非表示にしたい。以下は私のコードです:閉じるボタンをクリックすると角度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; 
    } 
} 
} 

Hideはコードでは動作しません。我々は簡単な方法でそれを行うことができますか?または最良のアプローチは何ですか?

答えて

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

更新

あなたがオブジェクトの配列またはアレイを使用しているかどうかは明確ではありませんでした。 はSO私は文字列の配列を持つオブジェクト

アレイのあなた溶液を得、* ngForループを持つ要素を非表示にすることはできません。あなたができるのはスプライスです。

ここで両方の方法を確認してください。

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

+0

ありがとう@micronyks。実際には、必要に応じてページに追加した後にテキストを削除したいと考えています。私はちょうどトグルを使用して達成するためにそれを試みた。残念ながら私にとっては、私は上記のように動作していません。 – Sunil

+0

最初の提案に従うことができます。それが動作します。あなたはtsファイルのclickイベント関数を必要としません。図のようにhTML自体から処理することができます。 – micronyks

+0

両方の提案の閉じるアイコンをクリックしても閉じることができません。 – Sunil

関連する問題