Ekrem Imamoglu, the mayor of Istanbul and a popular figure, had boasted jokingly that he was the only person to have beaten Recep Tayyip Erdogan’s ruling party in three local elections.