Where is the DMG saved when the hard disk is erased?
First of all, the process has evolved as newer versions of OS X and macOS have been released. Basically, you have the right idea. When booting to macOS Recovery, one or more ramdisks are created. The operating system then executes from these ramdisks. The drive (data carrier) where one wishes to install macOS can then be erased and formatted as an APFS container with a single volume. (This step is more complex when two drives are used in a fusion arrangement.) The installation files (which can consist of nested PKG and DMG files) are then downloaded from the internet. Recently, Apple published an article which gives some insight on how this may be accomplished. Here a private/tmp folder is created in the installation volume. The curl command is used to download installation files to this folder. The installation proceeds until the Mac boots to the newly installed Big Sur. Since the the installation files exist in private/tmp, these installation files are automatically erased at this point. The article refers to an installation on Macs with the M1 chip, however the downloaded software is also compatible with Macs with Intel processors.
The use of ramdisks, when either installing or booting to recovery, is not unique to macOS. When installing Linux, Grub executes an initrd command which loads a ramdisk file to memory. Windows loads a ramdisk file which is assigned the drive letter X:.