Magnesium chloride or MgCl2 is an ionic compound. Ionic compounds are formed due to the electrostatic force of attraction between oppositely charged ions.
Magnesium chloride is made of two types of ions, Mg2+ and Cl-. One atom of magnesium has 12 electrons. If it loses two electrons, the number of electrons left is 10 and the last shell has 8 electrons which is a stable configuration. Similarly, an atom of chlorine has 17 electrons and is one electron short from achieving 8 elctrons in its last electron shell that would create a stable configuration. To accomplish this chlorine takes on an extra electron and is converted to a Cl- ion.
Mg2+ and Cl- are attracted to each other due to the charges present on them. With the creation of MgCl2, the net charge becomes 0 and the molecule of MgCl2 is left with a neutral charge.