我正在 Angular 5 中使用 *IF-else 语句。如果授权值为 true,则模板 2 应该呈现,如果模板 1 不应该呈现的话。这是代码
<div *ngIf="authorized; then picUrl else login"></div>
<ng-template #login>
<button mat-raised-button color="accent" class="mdl-cell mdl-cell--12-col mdl-color-text--white" style="background: #033342" (click)="openDialog()">Login</button>
</ng-template>
<ng-template #picUrl>
<img src="{{_loginVM.profilePic}}" class="img-thumbnail" alt="profile pic">
</ng-template>
调用社交组件
<social></social>
App.component.ts
export class AppComponent {
public authorized: boolean = false;
}
社交组件.ts
import { AppComponent} from '../app/app.component'
export class SocialComponent {
private _appComponent: AppComponent;
constructor(private socialAuthService: AuthService, appComponent: AppComponent,
public dialogRef: MatDialogRef<SignInSignUpDialogHomeComponent>) {
this._appComponent = appComponent;
}
public socialSignIn(socialPlatform: string) {
let socialPlatformProvider: any;
if (socialPlatform == "facebook") {
socialPlatformProvider = FacebookLoginProvider.PROVIDER_ID;
} else if (socialPlatform == "google") {
socialPlatformProvider = GoogleLoginProvider.PROVIDER_ID;
}
this.socialAuthService.signIn(socialPlatformProvider).then(
(userData) => {
if (userData != null) {
this._appComponent.authorized = true;
this._appComponent._loginVM.profilePic = userData.image;
this.dialogRef.close();
}
}
);
}
成功登录后该值更新为this._appComponent.authorized = true;
。该值不会反射(reflect)到 UI/UX。
我从这里找到了一些引用资料 https://angularfirebase.com/lessons/sharing-data-between-angular-components-four-methods/
我尝试过 BehaviorSubject<boolean>
。但不知道如何订阅UI数据绑定(bind)。难道,这就是我,必须要做的事?我不能直接对组件变量执行操作吗?
最佳答案
.html
<div *ngIf="authorized; then picUrl else login"></div>
组件.ts
ngOnInit() {
this.authorized= this.authService.isLoggedIn;
}
服务.ts
get isLoggedIn(): boolean {
return this.currentUser != null; //you can decide to return true or false
}
get currentuser(): user{
let user = localstorage.getitem('details')
return user;
}
关于javascript - Angular 从子组件更新 UI 将值反射(reflect)到父组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49144872/