Angular 9-错误TypeError:无法读取未定义的属性“名称”

时间:2020-05-15 18:46:33

标签: javascript angular angular-material

我正在尝试创建动态表单控件,我希望根据条件禁用某些控件,但是出现未定义的Type错误。 这是我的代码。

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;


     }


} 

现在,如果我不使用else条件,并且仅当它不给我错误但它仅呈现禁用的输入字段时,就可以使用。

这是我的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)

3 个答案:

答案 0 :(得分:3)

当您尝试在模板中访问temp1变量时,可能未定义该变量。您可以使用safe navigation operator ?.来解决该错误。

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

它会在尝试访问其属性之前检查是否定义了temp1[i]

答案 1 :(得分:1)

使用“猫王运算符”。防止属性路径中的未定义和空值非常有用。在不知道路径是否存在的情况下,使用此运算符可以导航对象路径。如果存在,则返回对象路径的值,否则返回空值。防止空引用异常非常有用。

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

代替

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

答案 2 :(得分:0)

也许是因为在渲染模板时 temp1 对象尚不存在,所以快速建议在所有需要检查temp1的情况下尝试更改此条件。 i] .name存在: ERROR: Command errored out with exit status 1: command: /home/femke/Programs/anaconda3/bin/python -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-rumwdmo2/multiprocessing/setup.py'"'"'; __file__='"'"'/tmp/pip-install-rumwdmo2/multiprocessing/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /tmp/pip-pip-egg-info-s25t8ebi cwd: /tmp/pip-install-rumwdmo2/multiprocessing/ Complete output (6 lines): Traceback (most recent call last): File "<string>", line 1, in <module> File "/tmp/pip-install-rumwdmo2/multiprocessing/setup.py", line 94 print 'Macros:' ^ SyntaxError: Missing parentheses in call to 'print'. Did you mean print('Macros:')? ---------------------------------------- ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. 那么如果temp1还不存在,您将不会收到任何错误:)。