I'm trying to show a phone number to a user, in a lightning web component, so that when they click on the number, it populates an input box.
LWCs have the lightning-formatted-phone component, however clicking on this triggers a click-to-dial event.
The specification for the component says it has a "click" method, but doing this:
<lightning-formatted-phone
value="+18005551212"
onclick={myHandler}>
</lightning-formatted-phone>
Doesn't fire myHandler
in the component, so I can't stopPropagation() nor preventDefault().
My question is how can I show a formatted phone number in a LWC with custom click behavior? Can this be achieved with the standard formatted phone input, or is there another Salesforce-y way to do this?
Best Answer
The
click-to-dial event
is coming from the standard HTML protocoltel:
. Your browser is looking for it and if available it tries to dial that phone number when you click on it. The<lightning-formatted-phone>
component looks like so when it builds in the browser:Source and Source2.
In order to prevent the
click-to-dial
action you need to get rid of thetel:
part of the<a>
element. Since this is an out of the box component provided by Salesforce this functionality is internally handled and you can't modify it.What you need to do, in order to prevent this from happening, is format the phone number yourself using a standard html element such as a
<span>
or a<div>
.I put a playground together to show you how you can easily mimic what the SF component does. You can check it out here.
All you have to do is add a
<span>
element and style it like so:HTML
<span class="phone-link" onclick={myHandler}>+18005551212</span>
CSS
However a potential complexity for you could be the formatting of the phone number yourself using JavaScript.