Short answer
To measure anchor links in Google Analytics 4 you will need to submit custom events either through GTAG or Google Tag Manager. This is because anchor links do not involve a page load and therefore do not automatically trigger the pageview event. In this article I explain how to achieve this.
Measure using Google Tag Manager
To measure clicks on anchor links using Google Tag Manager you must follow these steps.
Create a trigger for anchor links

This trigger must be for “Links only” and can only be activated for “clicks on Anchor links”. You can use the most convenient rule for your site, but generally speaking if you indicate that “Click URL contains #” it will be more than enough to recognize an anchor link.
Add a custom javascript variable

This custom variable will allow you to capture the anchor text of the clicks made on these links. You can call the variable anything. For this exercise we will call it “anchor text”.
Create a custom event tag

Create a custom GA4 event tag in Google Tag Manager to measure links. You just need to add the trigger you created, name the event with an appropriate description and add a custom parameter (in this case we used “anchor_text” to store the anchor text clicked on. It is important that you add this parameter later in GA4.
The JavaScript code to create the text variable is as follows:
function() {
var url = {{Click URL}}; // Click URL variable
var anchorText = url.split('#')[1]; // Extract anchor text
return anchorText ? '#' + anchorText : undefined; // return anchor text
}
Measure using GTAG
If you don’t use Google Tag Manager but your measurement depends on GTAG, you can insert this JavaScript code inside your website, which will automatically detect when a user clicks on an anchor text link, and whenever that happens, it will send a custom event to Google Analytics called “anchor_click” which will also include a custom parameter called “anchor_text” which will include the anchor text. Remember to add the parameter in GA4 to make it readable in your reports.
<script>
document.addEventListener('DOMContentLoaded', (event) => {
document.body.addEventListener('click', (event) => {
let target = event.target;
while (target != null && target.tagName != 'A') {
target = target.parentElement;
}
if (target && target.hash) {
gtag('event', 'anchor_click', {
'anchor_text': target.hash
});
}
});
});
</script>