【发布时间】:2022-08-24 18:49:37
【问题描述】:
我是 Angular 的新手。 @abacritt/angularx-social-login 中的 Google 按钮只是一个图标,我想通过将图标放在旁边带有“使用 Google 登录”字样的 div 中来更改其外观。我只需单击该图标即可通过 Google 进行身份验证,但我无法理解如何通过单击其外部 div 以编程方式单击它。我一直在尝试 ViewChild 但没有运气。 @abacritt/angularx-social-login 包带有<asl-google-signin-button></asl-google-signin-button> 元素,它在屏幕上显示图标。单击时,此元素将启动 Google 身份验证。
这是我的相关代码文件:
google-signin-button.component.html
<div (click)=\"clickGoogleBtn()\" class=\"google_signin\">
<asl-google-signin-button #googleBtnRef></asl-google-signin-button>
</div>
google-signin-button.component.ts
import { Component, OnInit, ViewChild} from \'@angular/core\';
import { SocialAuthService, SocialUser } from \'@abacritt/angularx-social-login\';
import {Router} from \'@angular/router\';
import { ElementRef } from \'@angular/core\';
@Component({
selector: \'app-google-signin-button\',
templateUrl: \'./google-signin-button.component.html\',
styleUrls: [\'./google-signin-button.component.scss\']
})
export class GoogleSigninButtonComponent implements OnInit{
@ViewChild(\'googleBtnRef\')
googleBtn?: ElementRef;
user?: SocialUser;
constructor(
private router: Router,
private socialAuthService: SocialAuthService) { }
ngOnInit(): void {
this.socialAuthService.authState.subscribe((user:SocialUser) => {
this.user = user;
console.log(user);
})
}
clickGoogleBtn() {
console.log(this.googleBtn);
const event = new MouseEvent(\'click\', {
view: window,
bubbles: false,
cancelable: true
})
this.googleBtn?.nativeElement.dispatchEvent(event);
}
-
click 事件很可能存在于内部元素上,而不是最外面的标签上。我看到你已经注入了
SocialAuthService,为什么不像他们概述的那样直接调用signInWithGoogle()? npmjs.com/package/@abacritt/angularx-social-login。如果您想单击元素而不是使用服务,则必须准确确定哪个元素具有事件,然后使用 vanilla JS 来选择它。 -
我认为您的评论缺少一些东西。
-
对于那个很抱歉。他们的自述文件说,对于使用 Google 登录,我们只需要使用按钮。 SocialAuthService.sign In(GoogleLoginProvider.PROVIDER_ID) 不起作用。 github.com/abacritt/angularx-social-login#readme
-
此外,当我深入了解 <asl-google-signin-button></asl-google-signin-button> 元素的子元素时,使用 console.log(this.googleBtn?.nativeElement.children[0].children [1]),我遇到了一个 iframe,但我不知道如何进一步向下钻取以单击其中的按钮。我什至不知道这是否可能。
-
我在两个不同的浏览器中查看了他们的演示,我发现带有 click 元素的 div 取决于您正在使用的浏览器......我个人我会寻找一个不同的库。提示:使用调试器单击
Elements选项卡中的元素,然后在控制台中执行$0.click()以查看它是否有任何作用。
标签: angular google-authentication viewchild