Ellipsis is the answer.
Ex: ...avoid it (from) happening again.
The preposition from has been omitted. It heads the prepositional phrase from happening. It takes the gerund happening as its object. Gerunds are nouns and prepositions need nouns.
a. to happen
to-infinitives can act as nouns but they aren't compatible with prepositions and can't act as their objects.
Happens is an inflected verb. Notice it ends in -s. Verbs are not compatible with prepositions either.
Happening is a gerund. It functions as a subject or an object.
Happened is a past participle. It functions as part of a verb, e.g., has happened.
All the best.