簡體   English   中英

Angular 9 - 錯誤類型錯誤:無法讀取未定義的屬性“名稱”

[英]Angular 9 - ERROR TypeError: Cannot read property 'name' of undefined

我正在嘗試創建一個動態表單控件,我希望根據條件禁用某些控件,但出現未定義的類型錯誤。 這是我的代碼。

ngOnInit(): void {

 this.dynamicForm = this.formBuilder.group({
      tickets: new FormArray([])
  });
  }
  get f() { return this.dynamicForm.controls; }
  get t() { return this.f.tickets as FormArray; }

       itemClick(node) {

for (let i = 0 ; i < this.data_tree.length; i++) {
         this.nestsort.push(Object.assign({}, ...function _flatten(o) { return [].concat(...Object.keys(o).map(k => typeof o[k] === 'object' ? _flatten(o[k]) : ({[k]: o[k]})))}(this.data_tree[i])))
      var check
         rights.forEach(element => {
          if(element == this.temp[i].id)
          {
           check = false
          }
          else{
            check = true;
          }


        });
         this.t.push(this.formBuilder.group({
          name: ({value: [this.nestsort[i][aisa]], disabled: check})   

  }));      




         this.temp1 = this.t.value;


     }


} 

現在,如果我不使用其他條件,並且僅當它不給我錯誤但它只呈現禁用的輸入字段時。

這是我的 HTML 代碼

<div *ngFor="let ticket of t.controls; let i = index">
              <div [formGroup]="ticket">
                  <div>
                      <mat-form-field *ngIf="temp1[i].name" appearance="outline"  style="width: 95%;">
                        <mat-label>{{temp[i].id}} </mat-label>
                      <input matInput type="text" placeholder="Name"  formControlName="name" class="form-control"/>
                      <!-- <mat-hint >Errors appear instantly!</mat-hint> -->
                    </mat-form-field>

我只想創建輸入字段,其中一些應該被禁用,因為用戶無權更改它,但它似乎無法創建這些字段並給我一個錯誤。 錯誤如下,

navbars.component.html:77 ERROR TypeError: Cannot read property 'name' of undefined
    at Object.updateDirectives (navbars.component.html:79)
    at Object.debugUpdateDirectives [as updateDirectives] (core.js:46970)
    at checkAndUpdateView (core.js:45981)
    at callViewAction (core.js:46347)
    at execEmbeddedViewsAction (core.js:46304)
    at checkAndUpdateView (core.js:45982)
    at callViewAction (core.js:46347)
    at execEmbeddedViewsAction (core.js:46304)
    at checkAndUpdateView (core.js:45982)
    at callViewAction (core.js:46347)

當您嘗試在模板中訪問它時,可能未定義temp1變量。 您可以使用安全導航運算符?. 解決錯誤。

<mat-form-field *ngIf="temp1[i]?.name" appearance="outline"  style="width: 95%;">

它會在嘗試訪問它的屬性之前檢查是否定義了temp1[i]

使用“貓王運營商”。 防止屬性路徑中的未定義和 null 值非常有用。 當我們不知道路徑是否存在時,此運算符允許我們導航 object 路徑。 如果 object 路徑存在,它返回值,否則返回 null 值。 防止空引用異常非常有用。

<mat-form-field *ngIf="temp1[i]?.name" appearance="outline" >

代替

<mat-form-field *ngIf="temp1[i].name" appearance="outline" >

也許是因為當模板呈現時temp1 object 還不存在,那么一個快速的建議,在所有需要檢查 temp1[i].name 是否存在的情況下嘗試將條件更改為此: *ngIf="temp1 && temp1[i] && temp1[i].name"然后如果 temp1 不存在,你不會得到任何錯誤:)。

暫無
暫無

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

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