Angular – Cannot read properties of undefined (reading 'find') in ng-select

huangapple go评论56阅读模式
英文:

Angular - Cannot read properties of undefined (reading 'find') in ng-select

问题

I will provide a translation of the code-related portion you mentioned:

我在我的Angular-15应用程序中有以下代码:

**component.ts**

```typescript
import { CountryService } from 'src/app/features/admin/services/country.service';

export class CountryCreateComponent {

  countriesDatas!: any[];
  selectedCountryCode!: string;
  selectedCountryName!: string;
  showDiv: boolean = false;

  constructor(
    private fb: FormBuilder,
    private toastr: ToastrService
  ) {
  }

  createCountry() {
    this.createCountryForm = this.fb.group({
      CountryCode: ['', [Validators.required]],
      CountryName: ['', [Validators.required]],
    });
  }

  constructor(
    private fb: FormBuilder,
    private countryService: CountryService,
    private toastr: ToastrService,
    private bsModalRef: BsModalRef,
    private modalService: BsModalService
  ) {}

  ngOnInit(): void {;
    this.createCountry();
    this.loadAllCountries();
  }

  loadAllCountries(){
    this.countryService.getCountriesDropdown().subscribe({
      next: (res: any) => {
        this.countriesDatas = res.data;
        this.isLoading = false;
      }
    })
  }

  onCountryChange() {
    const selectedCountry = this.countriesDatas.find(
      (country) => country.countryCode === this.selectedCountryCode
    );
    this.selectedCountryName = selectedCountry
      ? selectedCountry.countryName
      : '';
  }
}

在ng-select更改时,我想将选定的CountryCode和CountryName填充到文本输入字段中。

component.html

<div class="form-group">
  <label for="Country">Country:</label>
  <ng-select
    [items]="countriesDatas"
    [selectOnTab]="true"
    [searchable]="true"
    bindValue="CountryCode"
    bindLabel="CountryName"
    placeholder="Select Country"
    [multiple]="false"
    [clearable]="true"
    [(ngModel)]="selectedCountryCode"
    (ngModelChange)="onCountryChange()"
    required
    formControlName="CountryCode"
  >
  </ng-select>
</div>
</div>

<div id="divshow">
 <div class="form-group">
  <input
    type="text"
    class="form-control"
    formControlName="CountryName"
    id="CountryName"
    [value]="selectedCountryName"
  />
 </div>
</div>

当ng-select更改时,我希望将选定的CountryName加载到

中的文本输入框中。

但我收到了此错误:

Cannot read properties of undefined (reading 'find')

并且指向:const selectedCountry = this.countriesDatas.find(

我应该如何解决这个问题?


Please note that I've translated the code portion as you requested, but resolving the error would require examining the actual code in detail. The error you mentioned is related to the "find" method, which suggests that "countriesDatas" might not be defined or initialized properly. You may need to ensure that "countriesDatas" is populated correctly in the "loadAllCountries" function before using it in "onCountryChange."

<details>
<summary>英文:</summary>

I am having this code in my Angular-15 application:

**component.ts:**

    import { CountryService } from &#39;src/app/features/admin/services/country.service&#39;;
    
    export class CountryCreateComponent {
    
      countriesDatas!: any[];
      selectedCountryCode!: string;
      selectedCountryName!: string;
      showDiv: boolean = false;
    
      constructor(
        private fb: FormBuilder,
        private toastr: ToastrService
      ) {
      }
    
      createCountry() {
        this.createCountryForm = this.fb.group({
          CountryCode: [&#39;&#39;, [Validators.required]],
          CountryName: [&#39;&#39;, [Validators.required]],
        });
      }
    
      constructor(
        private fb: FormBuilder,
        private countryService: CountryService,
        private toastr: ToastrService,
        private bsModalRef: BsModalRef,
        private modalService: BsModalService
      ) {}
    
      ngOnInit(): void {;
        this.createCountry();
        this.loadAllCountries();
      }
    
      this.loadAllCountries(){
        this.countryService.getCountriesDropdown().subscribe({
          next: (res: any) =&gt; {
            this.countriesDatas = res.data;
            this.isLoading = false;
          }
        })
      }
    
      onCountryChange() {
        const selectedCountry = this.countriesDatas.find(
          (country) =&gt; country.countryCode === this.selectedCountryCode
        );
        this.selectedCountryName = selectedCountry
          ? selectedCountry.countryName
          : &#39;&#39;;
      }
    }

I want to populate the text input fields with selected CountryCode and CountryName using ng-select dropdown.

**component.html**

    &lt;div class=&quot;form-group&quot;&gt;
      &lt;label for=&quot;Country&quot;
        &gt;Country:&lt;/label
      &gt;
      &lt;ng-select
        [items]=&quot;countriesDatas&quot;
        [selectOnTab]=&quot;true&quot;
        [searchable]=&quot;true&quot;
        bindValue=&quot;CountryCode&quot;
        bindLabel=&quot;CountryName&quot;
        placeholder=&quot;Select Country&quot;
        [multiple]=&quot;false&quot;
        [clearable]=&quot;true&quot;
        [(ngModel)]=&quot;selectedCountryCode&quot;
        (ngModelChange)=&quot;onCountryChange()&quot;
        required
        formControlName=&quot;CountryCode&quot;
      &gt;
      &lt;/ng-select&gt;
      &lt;/div&gt;
    &lt;/div&gt;

    &lt;div id=&quot;divshow&quot;&gt;
     &lt;div class=&quot;form-group&quot;&gt;
      &lt;input
        type=&quot;text&quot;
        class=&quot;form-control&quot;
        formControlName=&quot;CountryName&quot;
        id=&quot;CountryName&quot;
        [value]=&quot;selectedCountryName&quot;
      /&gt;
     &lt;/div&gt;
    &lt;/div&gt;

When the ng-select is onChanged, I want to load the selected CountryName into the text input in &lt;div id=&quot;divshow&quot;&gt;
    
But I got this error:

    Cannot read properties of undefined (reading &#39;find&#39;)

and it points at: const selectedCountry = this.countriesDatas.find(

How do I resolve this?

</details>


# 答案1
**得分**: 1

你可以稍微改变初始化你的应用程序的方式

  countriesDatas: any[] = [];
  selectedCountryCode: string = '';
  selectedCountryName: string = '';

不要告诉 TypeScript 你的未定义值不能为 null 或 undefined,只需设置一个默认值。接下来,我会检查你的订阅中 res.data 是否也不是 undefined。由于你使用了 any 类型, TypeScript 无法帮助你捕获错误,所以我建议设置一个与响应匹配的接口。


<details>
<summary>英文:</summary>

you can just initialize your app a bit different


countriesDatas: any[] =[];
selectedCountryCode: string = '';
selectedCountryName: string = '';


instead of telling the typescript that you undefined values cannot be null or undefined with `!`, just set a default value. Next thing i would check if `res.data` is not undefined as well in you subscription. Since you use any types you will get no help from typescript to help you catch bugs, so i suggest setting up the an interface matching the response.



</details>



huangapple
  • 本文由 发表于 2023年5月21日 06:32:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/76297582.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定