File

src/module/components/ngx-auth-firebaseui-user/user.component.ts

Metadata

selector ngx-auth-firebaseui-user
styleUrls ./user.component.scss
templateUrl ./user.component.html

Index

Properties
Methods
Inputs
Outputs

Constructor

constructor(auth: AngularFireAuth, authProcess: AuthProcessService, _fireStoreService: FirestoreSyncService, snackBar: MatSnackBar, config: NgxAuthFirebaseUIConfig)
Parameters :
Name Type Optional
auth AngularFireAuth No
authProcess AuthProcessService No
_fireStoreService FirestoreSyncService No
snackBar MatSnackBar No
config NgxAuthFirebaseUIConfig No

Inputs

appearance
Type : MatFormFieldAppearance
canDeleteAccount
Default value : true
canEditAccount
Default value : true
canLogout
Default value : true
editMode
Type : boolean

Outputs

onAccountDeleted
Type : EventEmitter<void>
onAccountEdited
Type : EventEmitter<void>
onSignOut
Type : EventEmitter<void>

Methods

changeEditMode
changeEditMode()
Returns : void
Async deleteAccount
deleteAccount()

Delete the account of the current firebase ngx-auth-firebaseui-user

On Success, emit the event and toast a msg!# Otherwise, log the and toast and error msg!

Returns : any
Protected initUpdateFormGroup
initUpdateFormGroup()
Returns : void
reset
reset()
Returns : void
Async save
save()
Returns : any
signOut
signOut()
Returns : void

Properties

Public auth
Type : AngularFireAuth
Public authProcess
Type : AuthProcessService
Public config
Type : NgxAuthFirebaseUIConfig
Decorators :
@Inject(undefined)
updateEmailFormControl
Type : FormControl
updateFormGroup
Type : FormGroup
updateNameFormControl
Type : FormControl
updatePasswordFormControl
Type : FormControl
updatePhoneNumberFormControl
Type : FormControl
import { Component, EventEmitter, forwardRef, Inject, Input, Output } from '@angular/core';
import { AngularFireAuth } from '@angular/fire/auth';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { MatFormFieldAppearance, MatSnackBar } from '@angular/material';
import { User } from 'firebase';
import { NgxAuthFirebaseUIConfig, NgxAuthFirebaseUIConfigToken } from '../../ngx-auth-firebase-u-i.module';
import { AuthProcessService } from '../../services/auth-process.service';
import { FirestoreSyncService } from '../../services/firestore-sync.service';
import { EMAIL_REGEX, PHONE_NUMBER_REGEX } from '../ngx-auth-firebaseui/auth.component';

@Component({
  selector: 'ngx-auth-firebaseui-user',
  templateUrl: './user.component.html',
  styleUrls: ['./user.component.scss']
})
export class UserComponent {

  @Input()
  editMode: boolean;

  @Input()
  canLogout = true;

  @Input()
  canEditAccount = true;

  @Input()
  canDeleteAccount = true;

  @Input()
  appearance: MatFormFieldAppearance;

  @Output()
  onSignOut: EventEmitter<void> = new EventEmitter();

  @Output()
  onAccountEdited: EventEmitter<void> = new EventEmitter();

  @Output()
  onAccountDeleted: EventEmitter<void> = new EventEmitter();

  updateFormGroup: FormGroup;
  updateNameFormControl: FormControl;
  updateEmailFormControl: FormControl;
  updatePhoneNumberFormControl: FormControl;
  updatePasswordFormControl: FormControl;

  constructor(
    public auth: AngularFireAuth,
    public authProcess: AuthProcessService,
    private _fireStoreService: FirestoreSyncService,
    private snackBar: MatSnackBar,
    @Inject(forwardRef(() => NgxAuthFirebaseUIConfigToken)) public config: NgxAuthFirebaseUIConfig
  ) { }

  protected initUpdateFormGroup() {
    const currentUser: User = this.auth.auth.currentUser;
    this.updateFormGroup = new FormGroup({
      name: this.updateNameFormControl = new FormControl(
        { value: currentUser.displayName, disabled: this.editMode },
        [
          Validators.required,
          Validators.minLength(this.config.nameMinLength),
          Validators.maxLength(this.config.nameMaxLength)
        ]
      ),

      email: this.updateEmailFormControl = new FormControl(
        {value: currentUser.email, disabled: this.editMode},
        [
          Validators.required,
          Validators.pattern(EMAIL_REGEX)
        ]),

      phoneNumber: this.updatePhoneNumberFormControl = new FormControl(
        {value: currentUser.phoneNumber, disabled: this.editMode},
        [Validators.pattern(PHONE_NUMBER_REGEX)])
    });

    this.updateFormGroup.enable();
  }

  changeEditMode() {
    this.editMode = !this.editMode;

    this.editMode ? this.initUpdateFormGroup() : this.reset();
  }

  reset() {
    this.updateFormGroup.reset();
    this.updateFormGroup.disable();
    this.updateFormGroup = null;
  }

  async save() {
    if (this.updateFormGroup.dirty) {
      const user = this.auth.auth.currentUser;
      // ngx-auth-firebaseui-user.updateProfile()
      // ngx-auth-firebaseui-user.updateEmail()
      // console.log('form = ', this.updateFormGroup);

      const snackBarMsg: string[] = [];

      try {
        if (this.updateNameFormControl.dirty) {
          await user.updateProfile({displayName: this.updateNameFormControl.value});
          snackBarMsg.push(`your name has been updated to ${user.displayName}`);
        }

        if (this.updateEmailFormControl.dirty) {
          await user.updateEmail(this.updateEmailFormControl.value);
          snackBarMsg.push(`your email has been updated to ${user.email}`);
        }

        if (this.updatePhoneNumberFormControl.dirty) {
          await user.updatePhoneNumber(this.updatePhoneNumberFormControl.value);
          console.log('phone number = ', this.updatePhoneNumberFormControl.value);
          snackBarMsg.push(`your phone number has been updated to ${user.phoneNumber}`);
        }

        if (this.config.enableFirestoreSync) {
          await this._fireStoreService.updateUserData(this.authProcess.parseUserInfo(user));
        }

      } catch (error) {
        this.authProcess.showToast(error && error.message ? error.message : error);
        console.error(error);
      }


      if (snackBarMsg.length > 0) {
        this.authProcess.showToast(snackBarMsg.join('\\n'));
      }
      // this.updateFormGroup.reset();
    }

    this.editMode = false;
  }

  signOut() {
    this.auth.auth.signOut()
      .then(() => this.onSignOut.emit())
      .catch(e => console.error('An error happened while signing out!', e));
  }

  /**
   * Delete the account of the current firebase ngx-auth-firebaseui-user
   *
   * On Success, emit the <onAccountDeleted> event and toast a msg!#
   * Otherwise, log the and toast and error msg!
   *
   */
  async deleteAccount() {
    try {
      const user = this.auth.auth.currentUser;

      // await this.authProcess.deleteAccount();
      await this.auth.auth.currentUser.delete();
      // if (this.config.enableFirestoreSync) {
      await this._fireStoreService.deleteUserData(user.uid);
      // }
      this.onAccountDeleted.emit();
      this.editMode = false;
      console.log('Your account has been successfully deleted!');
      this.authProcess.showToast('Your account has been successfully deleted!');
    } catch (error) {
      console.log('Error while delete user account', error);
      this.authProcess.showToast(`Error occurred while deleting your account: ${error.message}`);
    }
  }
}
<div *ngIf="auth.authState| async as user; then authenticated else none">

</div>

<ng-template #authenticated>
  <mat-card *ngIf="auth.user | async as user">
    <!--<form [formGroup]="updateFormGroup" >-->
    <!--card header-->
    <mat-card-header fxLayout="column" fxLayoutAlign="center center">

      <img mat-card-avatar [src]="authProcess?.getUserPhotoUrl()">

      <div *ngIf="user.emailVerified; then emailVerified else emailNotVerified"></div>
      <ng-template #emailVerified>
        <mat-icon color="primary"
                  matTooltip="email is verified"
                  matTooltipPosition="after">
          verified_user
        </mat-icon>
      </ng-template>
      <ng-template #emailNotVerified>
        <mat-icon color="warn"
                  matTooltip="email is not verified"
                  matTooltipPosition="after">
          warning
        </mat-icon>
      </ng-template>

    </mat-card-header>

    <!--card content-->
    <mat-card-content *ngIf="editMode; then edit else readonly">
    </mat-card-content>

    <ng-template #edit>
      <form [formGroup]="updateFormGroup" (submit)="save()">

        <mat-card-content fxLayout="column" fxLayoutAlign="center center">
          <div fxLayoutAlign="center">
            <button mat-raised-button color="warn" class="edit-button"
                    (click)="changeEditMode()">
              cancel
            </button>
          </div>

          <!--name-->
          <mat-form-field class="full-width" [appearance]="appearance">
            <mat-label>Name</mat-label>
            <input matInput
                   placeholder="Name"
                   [formControl]="updateNameFormControl">
            <mat-icon matSuffix>person</mat-icon>
            <mat-hint align="end" aria-live="polite"> {{ updateNameFormControl.value?.length }} / {{ config.nameMaxLength }} </mat-hint>
            <mat-error *ngIf="updateNameFormControl.hasError('required')">
              Name is required
            </mat-error>
          </mat-form-field>

          <!--email-->
          <mat-form-field class="full-width" [appearance]="appearance">
            <mat-label>E-mail</mat-label>
            <input matInput
                   placeholder="E-mail"
                   [formControl]="updateEmailFormControl">
            <mat-icon matSuffix>email</mat-icon>
            <mat-error *ngIf="updateEmailFormControl.hasError('required')">
              E-mail is required {{updateEmailFormControl.value}}
            </mat-error>
            <mat-error *ngIf="updateEmailFormControl.hasError('pattern')">
              Please enter a valid e-mail address {{updateEmailFormControl.value}}
            </mat-error>
          </mat-form-field>

          <!--phone number-->
          <mat-form-field *ngIf="false" class="full-width" [appearance]="appearance">
            <mat-label>Phone number</mat-label>
            <input matInput
                   type="tel"
                   placeholder="Phone number"
                   [formControl]="updatePhoneNumberFormControl">
            <mat-icon matSuffix>phone</mat-icon>
            <mat-hint align="end" aria-live="polite">
              The phone number is international. Therefore, it should start with a + sign or 00,
              followed by the country code, - and national number e.g: +49-12345678 or 0041-1234567890

              NOTE : the phone number must be a valid phone credential !!
            </mat-hint>
            <mat-error *ngIf="updatePhoneNumberFormControl.hasError('pattern')">
              Please enter a valid phone number
            </mat-error>
          </mat-form-field>

        </mat-card-content>

        <mat-card-actions fxLayout="column">
          <button mat-button
                  color="primary"
                  type="submit">
            Save changes
          </button>
        </mat-card-actions>
      </form>
    </ng-template>

    <ng-template #readonly>
      <div fxLayoutAlign="center">
        <button mat-raised-button color="primary" class="edit-button"
                (click)="changeEditMode()">
          edit
        </button>
      </div>

      <!--name-->
      <mat-form-field class="full-width" [appearance]="appearance">
        <mat-label>Name</mat-label>
        <input matInput
               placeholder="Name"
               [value]="user.displayName"
               [disabled]="!editMode">
        <mat-icon matSuffix color="primary">person</mat-icon>
      </mat-form-field>

      <!--email-->
      <mat-form-field class="full-width" [appearance]="appearance">
        <mat-label>E-mail</mat-label>
        <input matInput
               placeholder="E-mail" [value]="user.email"
               [disabled]="!editMode">
        <mat-icon matSuffix color="primary">email</mat-icon>
      </mat-form-field>

      <!--phone number-->
      <mat-form-field *ngIf="false" class="full-width" [appearance]="appearance">
        <mat-label>Phone number</mat-label>
        <input matInput
               placeholder="Phone number"
               [value]="user.phoneNumber"
               [disabled]="!editMode">
        <mat-icon matSuffix color="primary">phone</mat-icon>
      </mat-form-field>

      <mat-card-actions fxLayout="column">
        <button *ngIf="canLogout" mat-button color="primary" (click)="signOut()">Sign out</button>
        <button *ngIf="canDeleteAccount" mat-button color="warn" (click)="deleteAccount()">Delete account</button>
      </mat-card-actions>

    </ng-template>

  </mat-card>

</ng-template>


<ng-template #none>
  <mat-card class="none-card" fxLayout="row" fxLayoutAlign="center center">
    <mat-card-content fxLayout="row" fxLayoutAlign="center center">
      <mat-icon color="accent">warning</mat-icon>
      <span>You are not logged in!</span>
    </mat-card-content>
  </mat-card>
</ng-template>

./user.component.scss

.edit-button {
  margin: 1rem;
}

.full-width {
  width: 100%;
}

.cut-text {
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
}

.none-card {
  min-height: 430px;

  span {
    font-size: 24px;
    text-align: center;
    color: rgba(0, 0, 0, .54);
  }
}
Legend
Html element
Component
Html element with directive

result-matching ""

    No results matching ""