Angular2 클릭 요소 ID
클릭 이벤트가 있습니다.
<button (click)="toggle($event)" class="someclass" id="btn1"></button>
<button (click)="toggle($event)" class="someclass" id="btn2"></button>
내 함수 입력 파라미터에서 이벤트를 잡고 있는데 정확히 어떤 버튼이 클릭되었는지 알고 싶습니다.
toggle(event) {
}
그렇지만event가 없습니다.id소유물.
altKey: false
bubbles: true
button: 0
buttons: 0
cancelBubble: false
cancelable: true
clientX: 1198
clientY: 29
ctrlKey: false
currentTarget: button#hdrbtn_notificaton.mdl-button.mdl-js-button.mdl-js-ripple-effect.mdl-button--icon
defaultPrevented: false
detail: 1
eventPhase: 3
fromElement: null
isTrusted: true
isTrusted: true
layerX: -566
layerY: 5
metaKey: false
movementX: 0
movementY: 0
offsetX: 22
offsetY: 13
pageX: 1198
pageY: 29
path: Array[13]
relatedTarget: null
returnValue: true
screenX: 1797
screenY: 148
shiftKey: false
sourceCapabilities: InputDeviceCapabilities
srcElement: span.mdl-button__ripple-container
target: span.mdl-button__ripple-container
timeStamp: 1458032708743
toElement: span.mdl-button__ripple-container
type: "click"
view: Window
webkitMovementX: 0
webkitMovementY: 0
which: 1
x: 1198
y: 29
어떻게 찾을 수 있습니까?id?
업데이트: 플렁커는 모두 좋지만, 제 경우에는 현지에서:
event.srcElement.attributes.id- 미정의event.currentTarget.id- 가치가 있습니다.
크롬 최신버전 49.0.2623.87m를 사용하고 있습니다.
그럴 수 있을까요?Material Design Lite물건이요? 제가 쓰고 있으니까요.
액세스를 원하는 경우id당신이 활용할 수 있는 버튼의 속성.srcElement이벤트 속성:
import {Component} from 'angular2/core';
@Component({
selector: 'my-app',
template: `
<button (click)="onClick($event)" id="test">Click</button>
`
})
export class AppComponent {
onClick(event) {
var target = event.target || event.srcElement || event.currentTarget;
var idAttr = target.attributes.id;
var value = idAttr.nodeValue;
}
}
다음 플렁커: https://plnkr.co/edit/QGdou4?p=preview 를 참조하십시오.
다음 질문을 참조하십시오.
TypeScript 사용자의 경우:
toggle(event: Event): void {
let elementId: string = (event.target as Element).id;
// do something with the id...
}
드디어 가장 간단한 방법을 찾았습니다.
<button (click)="toggle($event)" class="someclass" id="btn1"></button>
<button (click)="toggle($event)" class="someclass" id="btn2"></button>
toggle(event) {
console.log(event.target.id);
}
정적 값(또는 변수)을 전달할 수 있습니다.*ngFor또는 무엇이든)
<button (click)="toggle(1)" class="someclass">
<button (click)="toggle(2)" class="someclass">
전체 이벤트를 통과할 필요는 없습니다(당신이 말한 이벤트의 다른 측면이 필요하지 않은 한).사실, 그것은 권장되지 않습니다.요소 참조를 약간의 수정만으로 통과할 수 있습니다.
import {Component} from 'angular2/core';
@Component({
selector: 'my-app',
template: `
<button #btn1 (click)="toggle(btn1)" class="someclass" id="btn1">Button 1</button>
<button #btn2 (click)="toggle(btn2)" class="someclass" id="btn2">Button 2</button>
`
})
export class AppComponent {
buttonValue: string;
toggle(button) {
this.buttonValue = button.id;
}
}
실제 요소를 통과했으므로 클릭한 버튼을 찾을 필요가 없습니다.
당신의HTMLElement없어요id,name아니면class전화를 드리자면,
그럼 쓰시오
<input type="text" (click)="selectedInput($event)">
selectedInput(event: MouseEvent) {
log(event.srcElement) // HTMInputLElement
}
인터페이스를 사용할 수 있습니다. HTMLButtonElement부모로부터 물려받은 것입니다.HTMLElement!
이렇게 하면 자동 완성이 가능합니다.
<button (click)="toggle($event)" class="someclass otherClass" id="btn1"></button>
toggle(event: MouseEvent) {
const button = event.target as HTMLButtonElement;
console.log(button.id);
console.log(button.className);
}
W3C(World Wide Web Consortium) 설명서의 모든 HTML 요소 목록을 보려면 다음과 같이 하십시오.
간단하게 이렇게 하십시오. (댓글에 언급된 바와 같이 두 가지 방법의 예입니다.)
import {Component} from 'angular2/core';
@Component({
selector: 'my-app',
template: `
<button (click)="checkEvent($event,'a')" id="abc" class="def">Display Toastr</button>
<button (click)="checkEvent($event,'b')" id="abc1" class="def1">Display Toastr1</button>
`
})
export class AppComponent {
checkEvent(event, id){
console.log(event, id, event.srcElement.attributes.id);
}
}
데모: http://plnkr.co/edit/5kJaj9D13srJxmod213r?p=preview
중첩 html의 경우 다음을 사용합니다.closest
<button (click)="toggle($event)" class="someclass" id="btn1">
<i class="fa fa-user"></i>
</button>
toggle(event) {
(event.target.closest('button') as Element).id;
}
속성의 값을 해당 이름으로 검색할 수 있으므로 지시문에서 속성과 같은 사용자 지정 속성의 값을 가져올 수 있습니다.
<button (click)="toggle($event)" id="btn1" myCustomAttribute="somevalue"></button>
toggle( event: Event ) {
const eventTarget: Element = event.target as Element;
const elementId: string = eventTarget.id;
const attribVal: string = eventTarget.attributes['myCustomAttribute'].nodeValue;
}
액세스를 원하는 경우id각 6의 버튼 속성은 이 코드를 따릅니다.
`@Component({
selector: 'my-app',
template: `
<button (click)="clicked($event)" id="myId">Click Me</button>
`
})
export class AppComponent {
clicked(event) {
const target = event.target || event.srcElement || event.currentTarget;
const idAttr = target.attributes.id;
const value = idAttr.nodeValue;
}
}`
당신의.id그 값으로,
의 가치value가myId.
아래와 같이 event.path를 사용할 수도 있습니다.
html:
<tbody>
<tr *ngFor="let r of rows" id="{{r}}">
<td>
<span>
<button (click)="deleteRow($event)" type="button"
class="btn-close"></button>
</span>
</td>
</tr>
</tbody>
ts:
deleteRow(evemt:any){
this.rows.pop()
console.log(evemt.path[3].id);
}
evmt.path[3].id 3은 1부터 액세스할 부모가 직계 부모입니다.
언급URL : https://stackoverflow.com/questions/36006894/angular2-get-clicked-element-id
'programing' 카테고리의 다른 글
| 자동 완성 목록에서 VBA 및 HTML로 항목 클릭 (0) | 2023.09.06 |
|---|---|
| Powershell: 사용자가 로그인하지 않았을 때 실행할 스케줄링된 작업 설정 (0) | 2023.09.06 |
| 레코드를 업데이트하는 동안 "ORA-00903: 잘못된 테이블 이름" 오류가 발생했습니다. (0) | 2023.09.01 |
| mysql 커넥터 오류 1130: 호스트가 이 MySQL 서버에 연결할 수 없습니다. (0) | 2023.09.01 |
| "오류 1329: 데이터 없음 - 0 행 가져오기, 선택 또는 처리"를 제거하는 방법 (0) | 2023.09.01 |
