The Chida explains that because Avraham’s parents worshiped Avoda Zara, he had some impurity which would come out as Yishmael. That’s why he took Hagar and had Yishmael, as in doing so, he got rid of that impurity.
It says ושרי אשת אברהם לא ילדה לו...הנה נא עצרני ה' מלדת..., Sarai, Avram’s wife, had borne no children. She had an Egyptian maidservant whose name was Hagar. And Sarai said to Avram, see now Hashem has restrained me from bearing; consort, now, with my maidservant, perhaps I will be built up through her. And Avram listened to the voice of Sarai.
Why does it say עצרני which implies something was preventing her? Seemingly she wasn’t able to give birth.
The students of the Arizal and the Rema Mipano teach that all those years Avraham and Sarah were married and didn’t have children, they created souls of converts. This is what is meant in the words לא ילדה לו, meaning to him (Avraham), Sarah didn’t give birth physically, but there were these souls of converts they created, albeit not physically. This is what is meant in הנה נא עצרני: really Sarah gave birth but it wasn’t a physical birth. There was a prevention in giving birth physically.
With this we can explain ולה שפחה מצרית ושמה הגר, she had an Egyptian maidservant whose name was Hagar, meaning Hagar can be understood as related to the word ger, convert (הגר). Sarah thought geirim would come from her and in the merit of giving Hagar to Avraham, Sarah thought she herself would also have physical geirim come from her. But because of all the impurity of Hagar, הגר was turned around into גרה, which shares identical letters, and therefore Yishmael emerged from her, who is in the category of גרהמעלה.
All the impurity of Avraham from his parents came out with Hagar and Yishmael. Now, when Avraham was 100 and Sarah 90 and their fire of life left them with their old age and they lived a life full of kedusha, then the holy Yitzchak emerged from them. This is what is meant in לא ילדה לו, meaning because of Avraham. That is to say, he first needed to get rid of the impurity. Sarah didn’t give birth with him until he got rid of that impurity, by him first having Yishmael. This is the explanation in הנה נא עצרני, meaning because he had this impurity and therefore took Hagar and got rid of that impurity, and then אולי אבנה, then I will get pregnant from holy seed.
With this we can explain the reason that Sarah put an ayin hara in the first pregnancy of Hagar and she miscarried. This is because she knew with Ruach Hakodesh that the first pregnancy was bad from the intense impurity. She therefore intentionally caused the miscarriage. Then Hagar gave birth to Yishmael, who had good in him, and therefore did teshuva later in life.