Is it possible for a phone to still be compromised/infected by malware or spyware even after a factory reset? If yes then how can one ensure that its %100 wiped clean?
Android 7 | rooted
EDIT: Same question but how about when rom is flashed
?
Yes, it's entirely possible if

the malware/Trojan resides and or modifies /system partition (search would show it's not uncommon) .

Thanks to Firelord who pointed out another possibility of



cases where an update to system introduced a persistent system level malware (usually a spyware, adware type), or one or two system apps (usually system update apps) acted like a malware right from the time a user started using the device. (see 1, 2, 3, 4, 5 as examples)

By doing a factory-reset, you are only removing user installed apps and data. The only solution for the first case is to install stock ROM (if you are on stock) or install a custom ROM by clean flash (usually, OEMs /custom ROM providers give detailed instructions on this). By installing a ROM, the /system is wiped clean and installed, getting rid of the trouble.
If you are a victim of the second case, there isn't much you can do unless you find another ROM for your device.
Of course, you need to review your apps and make sure you don't install from unverified sources and take precautions to not get into this situation again.