The atomic number of magnesium(Mg) = 12
The electronic configuration of 12 Mg = 2,8,2
The atomic number of chlorine(Cl) = 17
The electronic configuration of 17 Cl = 2,8,7
Mg transfer its two electrons to each Cl, so that it can
achieve noble gas configuration (2,8) whereas each Cl accepts one electron from Mg so that both can achieve noble gas
configuration as shown below: