Framework/Angular

[Angular] SVG path element click 이벀트 ν•¨μˆ˜ μ‹€ν–‰ν•˜λŠ” 방법

yuri lee 2023. 4. 10. 08:39
λ°˜μ‘ν˜•

Intro

μ•ˆλ…•ν•˜μ„Έμš”. μ•΅κ·€λŸ¬μ—μ„œ SVG path element에 click 이벀트 ν•¨μˆ˜ μ‹€ν–‰ν•˜λŠ” 방법에 λŒ€ν•΄ μ•Œμ•„λ³΄λ„λ‘ ν•˜κ² μŠ΅λ‹ˆλ‹€. 

 

 

My Case

제 μΌ€μ΄μŠ€μ˜ 경우 νŠΉμ • SVG μš”μ†Œλ₯Ό ν΄λ¦­ν–ˆμ„ λ•Œ ν•¨μˆ˜λ₯Ό ν˜ΈμΆœν•˜λ„λ‘ ν•˜κ³  μ‹Άμ—ˆμŠ΅λ‹ˆλ‹€. λ”°λΌμ„œ μ•„λž˜μ™€ 같이 κ΅¬ν˜„ν•˜μ˜€μŠ΅λ‹ˆλ‹€. 

 

  • svg νŒŒμΌμ€ λ‹€μŒκ³Ό κ°™μŠ΅λ‹ˆλ‹€.
<path #myPath (click)="handleClick()" class="cls-2" d="..." transform="..."/>

 

 

  • ts νŒŒμΌμ€ λ‹€μŒκ³Ό κ°™μŠ΅λ‹ˆλ‹€.
  @ViewChild('myPath') myPath: ElementRef;

  handleClick() {
    console.log("handleClick!!");
  }

 

ν•˜μ§€λ§Œ, svg 파일의 path μš”μ†Œλ₯Ό 클릭해도  handleClick ν•¨μˆ˜κ°€ λ™μž‘ν•˜μ§€ μ•Šμ•˜μŠ΅λ‹ˆλ‹€. 

 

 

Why?

클릭 μ΄λ²€νŠΈκ°€ λ°œμƒν•˜μ§€ μ•ŠλŠ” λ¬Έμ œλŠ” 쑰건이 μΆ©μ‘±ν•˜μ§€ μ•Šμ•˜κΈ° λ•Œλ¬Έμž…λ‹ˆλ‹€. 클릭 이벀트λ₯Ό μ²˜λ¦¬ν•˜κΈ° μœ„ν•΄μ„œλŠ” ν•΄λ‹Ή μš”μ†Œκ°€ 클릭이 κ°€λŠ₯ν•œ μƒνƒœμ—¬μ•Ό ν•˜κΈ° λ•Œλ¬Έμž…λ‹ˆλ‹€. path μš”μ†ŒλŠ” 기본적으둜 클릭이 κ°€λŠ₯ν•œ μš”μ†Œκ°€ μ•„λ‹ˆλΌκ³  ν•©λ‹ˆλ‹€. λ”°λΌμ„œ 이λ₯Ό 클릭 κ°€λŠ₯ν•œ element둜 λ§Œλ“€μ–΄μ€˜μ•Ό ν•©λ‹ˆλ‹€. 

 

참고둜 path μš”μ†Œ μ˜λ―ΈλŠ” μ•„λž˜μ™€ κ°™μŠ΅λ‹ˆλ‹€. 

The <path> element is the most powerful element in the SVG library of basic shapes. It can be used to create lines, curves, arcs, and more.

 

How to solve the problem

1. path μš”μ†Œμ— pointer-events 속성을 μΆ”κ°€ν•˜μ—¬ 클릭 κ°€λŠ₯ν•˜λ„λ‘ μ„€μ •ν•©λ‹ˆλ‹€.

<path #myPath class="cls-2" d="..." pointer-events="visible" transform="..."></path>

 

2. pointer-events 속성을 μΆ”κ°€ν•œ path μš”μ†Œλ₯Ό svg νƒœκ·Έλ‘œ κ°μ‹Έμ„œ svg μš”μ†Œλ₯Ό 클릭 κ°€λŠ₯ν•˜λ„λ‘ λ§Œλ“€μ–΄μ€λ‹ˆλ‹€. 

<svg (click)="handleClick()">
  <path #myPath class="cls-2" d="..." pointer-events="visible" transform="..."></path>
</svg>

 

 

 


https://developer.mozilla.org/en-US/docs/Web/SVG/Tutorial/Paths

λ°˜μ‘ν˜•