2016-09-23 2 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; 
    } 
} 
} 

코드에서 작동하지 않습니다. 우리는 간단한 방식으로 그것을 할 수 있습니까? 또는 최선의 접근 방법은 무엇입니까?

답변

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. 

또는

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

업데이트 : 당신이 배열 또는 객체의 배열을 사용하고 있는지

당신은 명확하지 않았다. 그래서 난 문자열 배열로 객체

배열의 당신이 솔루션을 준, * ngFor 루프 요소를 숨길 수 없습니다. 당신이 할 수있는 일은 스플 라이스입니다.

두 가지 방법을 모두 확인하십시오.

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

+0

감사 @micronyks. 사실, 필자는 필요할 경우 페이지에 추가 한 다음 텍스트를 삭제하려고합니다. 난 그냥 토글을 사용하여 달성하기 위해 노력했습니다. 불행히도 나를 위해, 내가 위에서 말한 것처럼 작동하지 않습니다. – Sunil

+0

첫 번째 제안을 따르십시오. 효과가있을 것입니다. ts 파일에서 click 이벤트 기능을 필요로하지 않습니다. 그림과 같이 hTML 자체에서 처리 할 수 ​​있습니다. – micronyks

+0

두 가지 제안에서 닫기 아이콘을 클릭 한 후에 닫을 수 없습니다. – Sunil

관련 문제