簡體   English   中英

錯誤TypeError:無法讀取未定義的屬性'stateName'

[英]ERROR TypeError: Cannot read property 'stateName' of undefined

看到我的要求是,當我單擊特定行時應該有一個表格時,數據應該出現在模態中,如圖2所示。我正在獲取文本框值,但沒有獲得下拉值,我的數據在圖的右側控制台窗口中。 2 在此處輸入圖片說明 在此處輸入圖片說明

我有這樣的json格式的數據

{
id: 1,
cityName: "Au", 
active: 1, 
state: { 
        id:1,
        stateCode:"AU",
        stateName:"Auguest"
       }
}

我想將stateName綁定到輸入字段中,如何實現它

  <div installerModal #modalCityView="installerModalEle" class="main-register-wrap modal" style="background-color: #fafafa;padding-top:150px;padding-right:10%;">
<div class="main-overlay"></div>
  <div class="main-register-holder">
    <div class="main-register fl-wrap" style="width:800px;height:450px">
      <div (click)="modalCityView.close()" class="close-reg">
        <i class="fa fa-times" ></i>
      </div>
      <div class="header-inner">
        <h3> <span style="font-weight:700">View <strong>City</strong>  </span></h3>
      </div>
      <div class="custom-form">
        <form novalidate class="row" [formGroup]="form" (ngSubmit)="onSubmit(form.value)"><br /><br />
          <label>Select State Name</label><br />

          <div class="container">
            <select class="form-control form-control-lg" formControlName="Name" name="stateRows">
              <option selected="selected" >{{selectedcity.state.stateName}}</option>
              <option *ngFor="let names of rows" >{{names.stateName}}</option>
            </select>
          </div>
          <div class="container" style="padding-top: 35px;">
            <label>City Name <span style="color:red">*</span> </label>
            <input name="text" type="text" [(ngModel)]="selectedcity.cityName" formControlName="citName" value="" required>
          </div>
          <div class="btn-toolbar" role="toolbar" aria-label="Toolbar with button groups" style="padding-left:500px;padding-top: 15px;">
            <div class="btn-group mr-2" role="group" aria-label="First group">
              <button type="submit" type="button" (click)="modalCityView.close()" (click)="onAddCity()" class="btn1 btn-secondary"><b>Save</b></button>
            </div>
            <div class="btn-group mr-2" role="group" aria-label="Second group">
              <button type="button" id="cancel" (click)="modalCityView.close()" style="cursor:pointer;" class="btn1 btn-secondary"><b>Cancel</b></button>
            </div>
          </div>
        </form>
      </div>
    </div>
  </div>

這是我的html代碼,在{{selectedcity.state.stateName}}的位置,我想獲取狀態名稱,但是每當我嘗試綁定該值時,我都會收到錯誤消息,因為“無法讀取未定義的屬性'stateName'” 。

import { Component, OnInit, ViewChild,AfterViewInit,ChangeDetectorRef } from 
"@angular/core";

import { FormBuilder, FormGroup, Validators, FormControl, 
ReactiveFormsModule, FormsModule, } from '@angular/forms';
import { HttpClient } from "@angular/common/http";

import {PostGetService} from '../../../services/PostGet.service';




 @Component({
    selector: 'user-location',
    templateUrl: './component.html',
    styleUrls: ['./component.scss'],
    providers: [LocationService,PostGetService]
 })

export class LocationComponent implements OnInit{
   @ViewChild('modal') signModal: InstallerModalDirective;
   @ViewChild('modal1') signModal1: InstallerModalDirective;
   rows: any[];
   cities: any[];
   stateRows: any[];
   cityRows: any[];
    postalRows: any[];
   form;
   formErrors: any;
   staName: string[];
  statCode:string[];
  citName: string[];
  csName: Object = {};
  NamesList;
  states: any[];
  viewCode:string[];
  city: string[];
  selected:any={};
  selectedcity:any={};
  stateName:any={};
  state: any={}

  constructor(private locService: LocationService,private 
 stateService:PostGetService,private changeDetectorRefs: ChangeDetectorRef){
    changeDetectorRefs.detach();
setInterval(() => {
  this.changeDetectorRefs.detectChanges();
}, 2000);
}

updatedStates(){
    this.stateService.getAllStates()
    .subscribe(data => {
        this.rows = data.json();
        console.log(this.rows)
    });

}

updatedCities(){
    this.stateService.getAllCities()
        .subscribe(data => {
            this.cities = data.json() ;
            console.table(this.cities);
        });
}

updatedPostal(){
    this.locService.getPostalCode()
        .subscribe(data => {
            this.postalRows = data;
            console.log(this.postalRows);
        });
}

refresh() {
    this.changeDetectorRefs.detectChanges();

  }

  onSelect(state){
    this.selected = state;
    console.log(state);
  }

  onSelectCity(city){
    this.selectedcity = city;
    console.log(city);
  }


ngOnInit(){
    this.form = new FormGroup({
        stateName: new FormControl("", Validators.compose([
            Validators.required,
            Validators.pattern("^[A-Za-z\\s]+$")
        ])),
        stateCode: new FormControl("", Validators.compose([
            Validators.required,
            Validators.pattern("^[A-Za-z\\s]+$")
        ])),
        Name: new FormControl("", Validators.required),
        statName: new FormControl(""),
        citName: new FormControl("", Validators.compose([
            Validators.required,
            Validators.pattern("^[A-Za-z\\s]+$")
        ])),
        postCode: new FormControl("", Validators.compose([
            Validators.pattern("^[0-9]{5,6}$"),
        ])),
    //     'power': new FormControl(this.hero.power, Validators.required)
    // },  { validators: identityRevealedValidator });
    });
    this.locService.getCityTableData()
    .subscribe(states => {
        this.NamesList = states;
        console.log(this.NamesList);
      });

this.updatedStates();
this.updatedCities();
this.updatedPostal();
this.refresh()

}

onAddState(){
    const stateData ={"stateName":this.staName,"stateCode":this.statCode}
    this.stateService.saveStates(stateData).subscribe(res=>{
        console.log(res);
        this.stateService.getAllStates();
        this.updatedStates();
        this.ngOnInit();
    });
    this.updatedStates();
    console.log(this.rows)
    this.ngOnInit();
}

onAddCity(){
    const cityData={
        state:{
          id:Number(this.csName)
        },
        cityName:this.citName,
    }
    const d = JSON.stringify(cityData);
    console.log(d);
    this.stateService.saveCities(d).subscribe(res => {
        console.log(res);
        this.stateService.getAllCities();
        this.updatedCities();
        this.ngOnInit();
    });
    this.updatedCities();
    this.ngOnInit();
}



onSubmit(){
    console.log("details");
}


}
replace {{selectedcity.state.stateName}} with {{selectedcity?.state?.stateName}}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM