2017-12-20 8 views
1
아래의 HTML

이벤트 위임이

<ul> 
    <li><span>hello</span><button>button</button></li> 
</ul> 

을 가진 고려 각 2

에서 특정 대상에 대한 이벤트 위임을 구현 그리고 내가 리튬 경우에도을 대상으로 이벤트 위임을 구현하려는 방법

사용자가 li의 스팬이나 버튼을 클릭하면 li 이벤트가 실행됩니다.

예를 들어 우리가 사용 JQuery와에이를 수 있습니다

$('ul').on('click', 'li', function() { 
    console.log($(this)) // always log the li whenever you clicked inside it 
}) 

내 실제 시나리오를 각도에 :

<div class="list-group" (click)="selectOption($event)"> 

<button type="button" class="list-group-item" *ngFor="let option of options; let i = index" 
[attr.data-value]="option.key" [attr.data-label]="option.displayColumnValue"> 
    <span [title]="option.displayColumnValue "> 
    {{ option.displayColumnValue }} 
    <small *ngIf="option.email">({{ option.email }})</small> 
    </span> 

    <a *ngIf="option.group" class="drilldown" [attr.data-key]="option.key"><i class="fa fa-chevron-right" aria-hidden="true"></i></a> 
</button> 

+0

죄송합니다 왜 귀하의 clikkable 영역을 모두 div로 감싸고 클릭 이벤트를 넣지 마십시오? –

+1

ul 요소의 (click) 이벤트에 함수를 바인딩 할 수 있지만,이 옵션을 사용하면 어떤 요소가 여분의 로직 인 –

+0

을 클릭했는지 제어 할 수 없으므로이를 달성하기위한 옵션이 제공되지 않습니다. 직접 처리하십시오. –

답변

2

당신이 @HostListner

와 지침을 작성하여이를 achive 수 있습니다
@Directive({selector: '[dele]') 
export class delegator{ 
    @HostListener('click') clicked($event) { 
     console.log($event.target); // this will be a child button 
    } 
} 

이제뿐만 아니라 지시문을 추가 한 후 HTML에서 이벤트

@Directive({ 
    selector: "[dele]" 
}) 
export class deleDirective { 
    @Output() onFocusOut: EventEmitter<boolean> = new EventEmitter<false>(); 

    @HostListener("focusout", ["$event"]) 
    public onListenerTriggered(event: any): void { 
     this.onFocusOut.emit(true); 
    } 
} 

을 사용하여 특정 요소에 hostlistner를 추가하려면이

<ul dele> 
    <li><span>hello</span><button>button</button></li> 
</ul> 

편집

과 같이 호출

<ul> 
     <li dele (onFocusOut)='clickFunction($event)'><span>hello</span><button>button</button></li> 
</ul> 
+0

나는 그 안에있는 버튼이 아니라 li을 타겟으로하고 싶다. –

+0

$ ('ul'). on ('click', 'li', function() { console.log ($ 당신이 그것을 안으로 클릭 할 때마다 리 } –

+0

@ bahaalmomani 편집 내 확인에 –