The suspects spotted the police from a window and shot at them, chanting loudly in Arabic, the Interior Ministry said. No police officers were hurt by the gunfire.
Over the next two hours, police evacuated as many people as they could from the building and surrounding area and prepared for an assault on the apartment.
"The special police agents prepared to storm the building and when they started to execute the plan, the terrorists set off a powerful explosion, blowing themselves up," Interior Minister Angel Acebes said.
"There are three that could have blown themselves up, but the possibility of more is not ruled out," he said.
The news agency Europa Press said forensic specialists were searching the building's swimming pool for remains of a possible fourth suspect, but the report could not immediately be confirmed.
Police believe some of the suspects may have carried out the March 11 bombings, Acebes said.
After the blast, floodlights lit up the wreckage in the exposed rooms of the building. Pieces of concrete littered the floors and wires dangled from the ceilings.
Leganes, about 10 miles southwest of central Madrid, is home to 175,000 people.
The investigation into the March 11 attacks has focused on the Moroccan Islamic Combatant Group, which has links to Al Qaeda.
The Moroccan organization is related to a group suspected in last year's Casablanca bombings, which killed 45 people, including 12 suicide bombers.
Judge Juan del Olmo, the investigating magistrate, has issued international arrest warrants for five Moroccans and a Tunisian, identified as Sarhane Ben Abdelmajid Fakhet, and described as the leader of the bombers.
Another 15 suspects are already in custody. Six have been charged with mass murder and nine with collaborating with or belonging to a terrorist group. Eleven of the 15 charged are Moroccan.
Earlier yesterday, Acebes said a bomb found under the tracks of a high-speed train line on Friday was made of the same brand of explosive, Goma 2 Eco, that was used in the Madrid train attacks.
However, he said it was still too early to name any suspects. Goma 2, often used for demolition and in mining, is relatively easy to get in Spain.