Как сделать так, чтобы эти параметры отображали их значение

#javascript #html #angular

#javascript #HTML #angular

Вопрос:

У меня проблема. Это мое веб-приложение, над которым я работаю, и одна из его функций — получить некоторые данные о минералах и сохранить их в локальном хранилище Chrome. Проблема в том, что некоторые параметры не отображают их значение, которые были введены пользователем. Это то, что я получаю в разделе приложения localstorage: {"Name":"Calciu","Formula":"Ca","Class":null,"Price":"3","Currency":"RON","Units":"Grams","Quantity":"3","Dated":{"Date":null},"Details":null} . Там, где вы видите null, должны быть какие-то значения. Я гарантирую, что ввел в формы все значения, которые были необходимы. Ниже приведен код (есть несколько строк кода, которые прокомментированы, потому что я попробовал некоторые функции). Мне нужна ваша помощь, чтобы получить значения тех параметров, которые показывают null.

#add-mineral.component.ts

 import { Component, OnInit, ViewChild } from '@angular/core';
import { FormBuilder, FormControl, FormGroup, NgForm, NgModel, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { ButtonRadioDirective } from 'ngx-bootstrap/buttons';
import { TabsetComponent } from 'ngx-bootstrap/tabs';
import { IMineralBase } from 'src/app/model/imineralbase';
import { Mineral } from 'src/app/model/mineral';
import { MineralWorldService } from 'src/app/services/mineral-world.service';

@Component({
  selector: 'app-add-mineral',
  templateUrl: './add-mineral.component.html',
  styleUrls: ['./add-mineral.component.scss']
})
export class AddMineralComponent implements OnInit {

 // @ViewChild ('Form') addMineralForm!: NgForm
  @ViewChild('formTabs') formTabs!: TabsetComponent;

  addMineralForm!: FormGroup;
  nextClicked_Name!: boolean;
  nextClicked_Price!: boolean;
  nextClicked_Quantity!: boolean;
  nextClicked!: boolean;
  mineral = new Mineral();

  classMinerals: Array<string> = ['Silicates','Sulfides','Carbonates','Oxides','Halides','Sulfates','Phosphates','Native Elements']
  currency: Array<string> = ['RON','USD','EUR']
  units: Array<string> = ['Grams','Kilograms','Pounds']

   mineralView: IMineralBase = {
      id: null as any,
      Name: '',
      Formula: '',
      Price: '',
      Currency: '',
      Quantity: '',
      Units: '',
      BuySell: null as any,
      Class : '',
      Dated: '',
      Details:''
   };

  constructor(private fb:FormBuilder,private router: Router, private MineralWorldService: MineralWorldService) { }

  ngOnInit() {
    this.CreateAddMineralForm();
  }

    CreateAddMineralForm(){
      this.addMineralForm = this.fb.group({
        BasicDetails: this.fb.group({
            Name: [null, Validators.required],
            Formula: [null, Validators.required],
            Class: [null, Validators.required]

        }),
        PriceQuantityInfo: this.fb.group({
        Currency: [null, Validators.required],
        Price: [null, Validators.required],
        Units: [null, Validators.required],
        Quantity: [null, Validators.required]
        }),
        Dated: this.fb.group({
          Date: [null, Validators.required]
        }),
        Detailss: this.fb.group({
          Details: [null, Validators.required]
        })
      });
    }

   mapMineral():void {
     //this.mineral.id = this.id.value;
     this.mineral.Name = this.Name.value;
     this.mineral.Formula = this.Formula.value;
     this.mineral.Class = this.Class.value;
     this.mineral.Price = this.Price.value;
     this.mineral.Currency = this.Currency.value;
     this.mineral.Units = this.Units.value;
     this.mineral.Quantity = this.Quantity.value;
     this.mineral.Dated = this.Dated.value;
     this.mineral.Details = this.Details.value;
    // this.mineral.BuySell = this.BuySell.value;

   }


  onBack()
  {
    this.router.navigate(['/'])
  }

  onSubmit(Form: NgForm)
  {
    this.nextClicked =true;
    this.mapMineral();
    this.MineralWorldService.addMineral(this.mineral);
    // if(this.allTabsValid())
    // {
    //   console.log('Congrats, your mineral listed successfully on the website');
    //   console.log(this.addMineralForm)
    // }else {
    //   console.log('Please review the form and provide valid information');
    // }
    console.log(this.addMineralForm);

  }

  // allTabsValid():boolean {
  //   if(this.BasicDetails.invalid)
  //   {
  //     this.formTabs.tabs[0].active = true;
  //     return false;
  //   }
  //   if(this.PriceQuantityInfo.invalid)
  //   {
  //     this.formTabs.tabs[1].active = true;
  //     return false;
  //   }
  //   if(this.Dated.invalid)
  //   {
  //     this.formTabs.tabs[2].active = true;
  //     return false;
  //   }
  //   if(this.Details.invalid)
  //   {
  //     this.formTabs.tabs[3].active = true;
  //     return false;
  //   }
  //   return true;
  // }

  selectTab(NextTabId: number)
  {
    // this.nextClicked =true;
    // if (IsCurrentTabValid)
    // {
    //   this.nextClicked_Name = true;
    //   this.nextClicked_Price = true;
    //   this.nextClicked_Quantity = true;
    //   this.formTabs.tabs[NextTabId].active =true;
    // }
    this.formTabs.tabs[NextTabId].active =true;
  }
  //#region ( Getter Methods )
    //#region <FormGroups>
        get BasicDetails() {
          return this.addMineralForm.controls.BasicDetails as FormGroup;
        }
        get PriceQuantityInfo() {
          return this.addMineralForm.controls.PriceQuantityInfo as FormGroup;
        }
        get Dated() {
          return this.addMineralForm.controls.Dated as FormGroup;
        }
        get Detailss() {
          return this.addMineralForm.controls.Detailss as FormGroup;
        }
  //#endregion
    //#region <Form Controls>


        get Name() {
          return this.BasicDetails.controls.Name as FormControl;
        }
        get Formula() {
          return this.BasicDetails.controls.Formula as FormControl;
        }
        get Class() {
          return this.BasicDetails.controls.Class as FormControl;
        }
        get Currency() {
          return this.PriceQuantityInfo.controls.Currency as FormControl;
        }
        get Price() {
          return this.PriceQuantityInfo.controls.Price as FormControl;
        }
        get Quantity() {
            return this.PriceQuantityInfo.controls.Quantity as FormControl;
        }

        get Units() {
          return this.PriceQuantityInfo.controls.Units as FormControl;
        }

        get Date() {
          return this.Dated.controls.Date as FormControl;
        }

        get Details() {
          return this.Detailss.controls.Details as FormControl;
        }
//#endregion
//#endregion
}

 

#add-mineral.component.html

 <div class = "row mb-5">
 <div class = "col-9 shadow-lg p-0 bg-white">
<div class="card">
    <div class = "card-header">
       <h3>Sell a Mineral</h3>
    </div>
    <div class = "card-body" >
       <form (ngSubmit)='onSubmit()'  [formGroup]="addMineralForm">
        <!-- [formGroup]="addMineralForm" -->
        <div class = "tab-panel">
           <tabset class = "member-tabset"  #formTabs>
              <tab heading = "Basic Details" formGroupName="BasicDetails">
                <div class = "form-group col-12"  >
                  <label for = "name">Name</label>
                  <input type = "text" class = "form-control" formControlName = "Name"  ngModel [(ngModel)] = "mineralView.Name" >
                  <div class ="error-block" *ngIf = "Name.invalid amp;amp; (nextClicked_Name || Name.touched)">Please add the name of the mineral</div>
              </div>
              <div class = "form-group col-12">
                <label for = "formula">Formula</label>
                <input type = "text" class = "form-control" ngModel  formControlName="Formula" [(ngModel)] = "mineralView.Formula" >
            </div>
          <div class = "form-group col-12">
            <p>Class of Minerals</p>
            <div class = "btn-group" btnRadioGroup ngModel [(ngModel)] = "mineralView.Class" name = "class" [ngModelOptions]="{standalone: true}">
              <label *ngFor ="let cm of classMinerals"
              class = "btn btn-outline-dark text-central"
              [btnRadio]="cm" tabindex="0" role="button" name = "class"> {{cm}}
              </label>
            </div>
         </div>
        <div class = "form-group col-12">
           <button type = "button"    class = "btn btn-dark btn-block" [disabled]="!Name.valid" (click)="selectTab(1)" >Next</button>
        </div>
              </tab>
              <tab heading = "Price and Quantity" formGroupName="PriceQuantityInfo" >
                <div class = "form-group col-12">
                   <p>Currency</p>
                   <div class = "btn-group" btnRadioGroup ngModel [(ngModel)] = "mineralView.Currency" formControlName = "Currency" >
                     <label *ngFor ="let c of currency"
                     class = "btn btn-outline-dark mr-2"
                     [btnRadio]="c" tabindex="0" role="button" name = "Currency"> {{c}}
                     </label>
                   </div>
                </div>
                <div class = "form-group col-12">
                  <label for = "price">Price</label>
                  <input type = "text" class = "form-control" ngModel formControlName = "Price" [(ngModel)] = "mineralView.Price" >
                  <div class ="error-block" *ngIf = "Price.invalid amp;amp; (nextClicked_Price || Price.touched)">Please add the price of the mineral</div>
              </div>
              <div class = "form-group col-12">
                <p>Units of Mass</p>
                <div class = "btn-group" btnRadioGroup [(ngModel)] = "mineralView.Units" formControlName = "Units" >
                  <label *ngFor ="let m of units"
                  class = "btn btn-outline-dark mr-2"
                  [btnRadio]="m" tabindex="0" role="button" name = "Units"> {{m}}
                  </label>
                </div>
             </div>
              <div class = "form-group col-12">
                <label for = "quantity">Quantity</label>
                <input type = "text" class = "form-control" ngModel formControlName = "Quantity" [(ngModel)] = "mineralView.Quantity">
                <div class ="error-block" *ngIf = "Quantity.invalid amp;amp; (nextClicked_Quantity || Quantity.touched)">Please add mineral quantity</div>
            </div>
            <div class = "form-group col-12">
              <button type = "button" class = "btn btn-dark btn-block" [disabled]="!Price.valid amp;amp; !Quantity.valid" (click)="selectTab(2)" >Next</button>
              <button type = "button" class = "btn btn-dark btn-block" (click)="selectTab(0)" >Back</button>
           </div>
              </tab>
              <tab heading = "Dated from" >
                <div class = "form-group col-12"  >
                  <label for = "date">Possession/Avaialble from (DD/MM/YYYY)</label>
                  <input type = "text" placeholder = "Datepicker"  ngModel [(ngModel)]="mineralView.Dated" name="date" class = "form-control"  [ngModelOptions]="{standalone: true}" bsDatepicker [bsConfig]="{containerClass: 'theme-dark-blue', dateInputFormat: 'DD-MM-YYYY'}">
              </div>
                <div class = "form-group col-12">
                  <button type = "button" class = "btn btn-dark btn-block" (click)="selectTab(3)">Next</button>
                  <button type = "button" class = "btn btn-dark btn-block" (click)="selectTab(1)">Back</button>
               </div>
              </tab>

              <tab heading = "Other Details">
                <div class = "form-group col-12">
                  <label for = "details">Describe any details that may be useful</label>
                  <input type = "text" class = "form-control" ngModel [(ngModel)]="mineralView.Details" name = "OtherDetails" [ngModelOptions]="{standalone: true}">
              </div>
                <div class = "form-group col-12">
                  <button type = "button" class = "btn btn-dark btn-block" (click)="selectTab(4)">Next</button>
                  <button type = "button" class = "btn btn-dark btn-block" (click)="selectTab(2)">Back</button>
               </div>
              </tab>
              <tab heading = "Images" >
                <div class="form-group col-12">
                  <div class="photo-control">
                      <button class="mt-5" type="button">Upload</button> <br>
                      This is under construction
                  </div>
                </div>
                <div class = "form-group col-12">
                  <button type = "button" class = "btn btn-dark btn-block" (click)="selectTab(3)">Back</button>
                  <button type = "reset" class = "btn btn-dark btn-block" >Cancel</button>
                  <button type = "submit" class = "btn btn-dark btn-block" >Save</button>
               </div>
              </tab>
           </tabset>
        </div>
       </form>
    </div>
</div>
</div>
  <div class = "col-3 mr-auto">
    <div class = "card-header ">
    <h4 class = "text-white">Your Offer Preview</h4>
    </div>
     <div class = "shadow-lg p-3 bg-white ">
        <app-mineral-card [mineral]="mineralView" [hideIcons] = "true"></app-mineral-card>
     </div>
    </div>
  </div>

 

Комментарии:

1. Вы намеревались поместить в это два «s»? Detailss: this.fb.group...

2. да, потому что в противном случае я получаю эту `Информацию о дублирующемся идентификаторе`.»`