They may be ideological opposites, but President Donald Trump and Mayor Bill de Blasio have more in common than you might think.

Both were elected from large fields of contenders, both running against the establishment. Criticizing the establishment and casting himself as anti-elitist, Trump defeated a cast of mainstream Republicans and the mainstream Democrat, Hillary Clinton.

Criticizing the NYPD’s stop-and-frisk policy and casting himself as anti-police, de Blasio beat his mainstream opponent, then- City Council Speaker Christine Quinn, in the primary.

Both made misjudgments early in their terms. Trump is still making them. A major policy pronouncement — his executive order suspending immigration from seven Muslim-majority countries — was stayed by the courts. Many in the NYPD believe that what they saw as de Blasio’s anti-cop rhetoric created the environment that led to the fatal shootings of two officers.

Both face political trouble. The Manhattan district attorney’s office is investigating de Blasio’s fundraising practices, and federal prosecutors are probing whether the mayor or city officials gave preferential treatment to contributors in exchange for donations.

Trump’s firing of retired Lt. Gen. Michael Flynn may just be the beginning of investigations into Flynn’s and Trump’s Russian connections that could have lasting damage for his presidency, if not lead to impeachment.

Both remain captives of their inner selves. Trump seems unable to stop himself from tweeting off the cuff, and de Blasio cannot shake free of his radical predilections.

On Feb. 8, Trump attacked retailer Nordstrom after it said it would drop his daughter’s fashion line. He tweeted: “My daughter Ivanka has been treated so unfairly by @Nordstrom. She is a great person — always pushing me to do the right thing! Terrible!”

And de Blasio tweeted to laud President Barack Obama’s decision to commute the sentence of Oscar Lopez Rivera, a member of a Puerto Rican terrorist group responsible for 100 bombings in the 1970s and 1980s, including a bombing at Fraunces Tavern that killed four and another at Police Plaza that permanently injured three NYPD officers.

De Blasio tweeted: “Thank you POTUS . . . Congratulations for all who fought for this day.”