Home > Blockchain >  Problem with a variable undefined in a mat dialog text in Angular
Problem with a variable undefined in a mat dialog text in Angular

Time:10-04

I created a dialog using angular in order to collect a information and save it on my back-end.

The problem is when i will send it to my back-end, using my post method, the variable of the coment stay undefined. The variable in question is:

val: " "

this is my dialog ts file:

import { Component, OnInit, Inject } from '@angular/core'; import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog'; import { IstManagementService } from './../../core/services/ist-management.service'; import { ReasonpopupService } from 'ClientApp/app/core/services/reasonpopup.service';

@Component({

  selector: 'app-reasonpopup',   templateUrl: './reasonpopup.component.html',   styleUrls: ['./reasonpopup.component.css'] }) export class ReasonpopupComponent implements OnInit {
     val : " " 
 
    /* reason2 : string = this.reason */
  
     onSubmit() { this.MatDialogRef.close(this.val); }
  

 
  
     getValue(val:string){
    console.log(val)
      }


  constructor(
    private istManagementService: IstManagementService,
    public MatDialogRef: MatDialogRef<ReasonpopupComponent>,
    @Inject(MAT_DIALOG_DATA) public data: any,
    private shared:ReasonpopupService,
    

    ) { }
     ngOnInit(): void {
    
    this.shared.setMessage(this.val)   }

  reason :string   closeDialog() {
    this.MatDialogRef.close(false);   }
          
}

my html file:

<div>
  <div class="content-container">
    <mat-icon id="close-icon" (click)="closeDialog()">close</mat-icon>
    <span class="content-span full-width">{{ data.message }}</span>
  </div>
  <form #userForm="ngForm">
  <div class="input-reason">
    
      <mat-form-field class="example-full-width" appearance="fill" [style.width.px]=420 style="padding-bottom: 100px;" >
        <mat-label>Leave a comment</mat-label>

        <textarea
        [(ngModel)]="val"
          type="text"
          ngModel class="form-control"
          required
          #text
          minlength="3"
          class="form-control"
          name="tx"
          matInput
          placeholder="please describe the reason"
        ></textarea>
        <span *ngIf="text.invalid && text.touched" class="error">input the reason</span>
      </mat-form-field>
   
  </div>
  <button mat-raised-button id="no-button" [mat-dialog-close]="false">NO</button>
  <button
    mat-raised-button
    [disabled]="userForm.invalid"
    id="yes-button"
    (click)="onSubmit()" 
    (click)="getValue(text.value)"
    [mat-dialog-close]="data.text"
    cdkFocusInitial
  >
    YES
  </button>

    </form>
</div>

The method where i pass my variable as argument on the other component that have the post method

saveRow() {
        let addRowsRequest = {
            IstValues: this.dataSource.data.filter(r => r.editing)
            
        };
        console.log(this.val)
        this.istManagementService.postRecord(this.inputTable, addRowsRequest, this.val).subscribe(
            (res: any) => {
                console.log(this.dataSource.data.filter(r => r.editing));
                this.dataSource.data.push(this.dataSource.data.filter(r => r.editing));
                this.dataSource._updateChangeSubscription();
            }
        )
    }

My setter and getter service that i created to share the variable between the components

mport { ReasonpopupComponent } from './../../tasks/reasonpopup/reasonpopup.component';
import { Injectable } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';

@Injectable({
  providedIn: 'root'
})
export class ReasonpopupService {
val:string
  constructor(private messageDialog: MatDialog) { }

  openReasonDialog(msg: string) {
    return this.messageDialog.open(ReasonpopupComponent, {
      width: '570px',
      panelClass: 'confirm-dialog-container',
      disableClose: true,
      data: { message: msg }
    })
  }

  setMessage(data: string){
    this.val=data
    console.log(this.val)
  }

  getMessage(){
    return this.val
  }


}

and finally, my service that contain all the CRUD methods

import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { ISTGenericResponse } from '../../pages/ist-management/ist-generic-response';
import { environment } from 'ClientApp/environments/environment';


@Injectable({
    providedIn: 'root'
})
export class IstManagementService {


    constructor(private httpClient: HttpClient) { }


    public getGenericStaticTablesFiltered(inputTable: string, inputKey: string, inputValue: string, inputComparison: string): Observable<ISTGenericResponse> {
        var filter = "";
        if (inputKey && inputValue) {
            filter = "?key="   inputKey   "&value="   inputValue   "&comparison="   inputComparison;
            return this.httpClient.get<ISTGenericResponse>(environment.apiRoot   "/StaticTable/Filter/"   inputTable   filter);
        }
        else {
            return this.httpClient.get<ISTGenericResponse>(environment.apiRoot   "/StaticTable/"   inputTable);
        }
    }
    message:string
    setMessage(data: string){
        this.message=data
    }
    getMessage(){
        return this.getMessage
    }
   
    postRecord(inputTable: string, addRecord: any,  message:any ) {
        return this.httpClient.post(environment.apiRoot   "/StaticTable/Add/"   inputTable, addRecord,  message);
    }

    deleteRecord(inputTable: string, deleteRecord: any) {
        const headers = new HttpHeaders({ 'Content-Type': 'application/json; charset=utf-8' });
        return this.httpClient.request('delete', environment.apiRoot   "/StaticTable/Delete/"   inputTable, { body: deleteRecord, headers: headers });
    }

    editRecord(inputTable: string, editRecord: any): Observable<any> {
        const headers = new HttpHeaders({ 'Content-Type': 'application/json; charset=utf-8' });
        return this.httpClient.request('put', environment.apiRoot   "/StaticTable/Update/"   inputTable, { body: editRecord, headers: headers, });
  

}

}

Thank you in advanced

CodePudding user response:

according to this code, you are calling this.shared.setMessage(this.val) inside the ngOnInit() method of ReasonpopupComponent

which will always be undefined because ngOnInit() is only called on the initialization of the component before the user inputs any data.

what you need to do is to move this.shared.setMessage(this.val) inside onSubmit() method, so in the end it looks like this

export class ReasonPopupComponent implements OnInit {
  val = '';

  constructor(
    private istManagementService: IstManagementService,
    public MatDialogRef: MatDialogRef<ReasonPopupComponent>,
    @Inject(MAT_DIALOG_DATA) public data: any,
    private shared:ReasonpopupService,
  ) { }

  ngOnInit(): void {
  }

  onSubmit() {
    this.shared.setMessage(this.val);
    this.MatDialogRef.close(this.val);

  }
  
  closeDialog() {
    this.MatDialogRef.close(false);
  }
}

what would be even better, if your "other component" is the one opening the pop-up, you can make use of angular material dialog subscriber. as you see in onSubmit() method this.matDialogRef.close(this.val)is already called with the value. all you need to do is to subscribe to it on the "other component" like so.

dialogRef.afterClosed().subscribe(result => {
      console.log(result)
    });
  • Related