I developed a unique component specifically for integrating the Telegram login widget:
This component dynamically generates the script tag and includes the callback function loginViaTelegram(user)
:
@Component({
selector: 'app-telegram-login-widget',
template: `
<div #script style.display="none">
<ng-content></ng-content>
</div>`,
styleUrls: ['./telegram-login-widget.component.css']
})
export class TelegramLoginWidgetComponent implements AfterViewInit {
@ViewChild('script', {static: true}) script: ElementRef;
convertToScript() {
const element = this.script.nativeElement;
const script = document.createElement('script');
script.src = 'https://telegram.org/js/telegram-widget.js?5';
script.setAttribute('data-telegram-login', environment.telegramBotName);
script.setAttribute('data-size', 'large');
// Callback function in global scope
script.setAttribute('data-onauth', 'loginViaTelegram(user)');
script.setAttribute('data-request-access', 'write');
element.parentElement.replaceChild(script, element);
}
ngAfterViewInit() {
this.convertToScript();
}
}
To facilitate this process, I integrated the callback function loginViaTelegram
into the window
object (global space) using a dedicated service:
@Injectable({
providedIn: 'root'
})
export class TelegramLoginService {
init() {
window['loginViaTelegram'] = loginData => this.loginViaTelegram(loginData);
}
private loginViaTelegram(loginData: TelegramLoginData) {
// If the login should trigger view changes, run it within the NgZone.
this.ngZone.run(() => process(loginRequest));
}
}