Knowing two factors will get you close.
The first is knowing where certain notes are on he instrument - whichever one - in this case, guitar. That entails being able, initially, to play scales, in all keys. For now, major and minor will get you a fair way, and the patterns just move up or down, so, for example, if you can play two octaves of A major, then moving everything up a fret will let you play in B♭ major.
The second is being able to recogise intervals - the spaces in between two notes - how far away from each other they are, musically.
You can develop both these skills simultaneously, by yourself if needs be, playing and singing. You'll reach a point where you will hear two notes, and when you've found one, and the key, be able to play the other.It's not going to happen oernight, or after a year or two, but by working on these two skills, a couple of notes ata time, you'll get there. Good luck.
If you learn to play from the music, and rely on that or tab, there's a good chance you'll never be able to do the above. Dvers - please explain to us why you think this isn't true.