The diffraction grating is a transparent plate with very narrow lines on the surface.
Light (photons) like to go in the same phase. In the same phase, constructive interference occurs. If the phases are different, the waves cancel each other out.
The light that passes through the hole in the diffraction grating has the opportunity to spread in many ways, but it tries to match the phases of the waves because they want all the lights to go to the same state. Therefore, the light passing through the holes travels only at a certain angle, depending on the wavelength.