Diagnosis
This is almost always a worn or misaligned door strike—the little metal hook on the door that catches the latch inside the door frame. Over time, it can bend or wear down, or the plastic housing it sits in can crack.
How to Fix It
Inspect the door strike. Open the door and look at the metal hook on the door's edge. Try to wiggle it. If it's loose, the plastic housing is likely broken. You'll need to replace the entire door strike assembly (not a hugely common part, but available). If it looks intact, check alignment. Close the door slowly and watch if the hook cleanly engages the latch mechanism in the frame. You can slightly bend the hook with pliers for better engagement.
If That Didn't Work
The problem might be the door latch switch assembly inside the door frame. If that mechanism is broken or the micro-switch is faulty, it won't hold the strike. You'll need to remove the front panel to inspect it. A broken latch will be obvious.
Heads Up
Don't just keep slamming it. If the door isn't fully latched, the door switch won't engage, and the dryer won't start or will stop mid-cycle. Forcing it can crack the door glass or further damage the strike.