developer tip

Angular2 : 정의되지 않은 '이름'속성을 읽을 수 없습니다.

optionbox 2020. 12. 14. 08:06
반응형

Angular2 : 정의되지 않은 '이름'속성을 읽을 수 없습니다.


Angular2를 배우기 시작했습니다. angular.io에서 제공하는 Heroes Tutorial을 따라 왔습니다. 템플릿을 사용하는 HTML의 혼란에 짜증이 나서 그 자리에 템플릿 URL을 사용하고 HTML을 hero.html이라는 파일로 옮길 때까지 모든 것이 잘 작동했습니다. 생성되는 오류는 "정의되지 않은 '이름'속성을 읽을 수 없습니다."입니다. 이상하게도 ngFor가 배열의 개체 수에 따라 정확한 양의 "li"태그를 생성하도록 개체 배열을 가리키는 heroes 변수에 액세스 할 수 있습니다. 그러나 배열 개체의 데이터에는 액세스 할 수 없습니다. 또한 일부 텍스트를 포함하는 간단한 변수도 HTML에서 {{}} 대괄호를 사용하여 표시되지 않습니다 (제공된 코드 참조).

app.component.ts

import { Component } from '@angular/core';
@Component({
  selector: 'my-app',
  templateUrl: './hero.html',
  styleUrls:['./styles.css']
})

export class AppComponent {
  title = 'Tour of Heroes';
  heroes = HEROES;
  selectedHero:Hero;

  onSelect(hero: Hero):void{
      this.selectedHero = hero;
  }
}

export class Hero{
   id: number;
   name: string;
}

const HEROES: Hero[] = [
   { id: 1, name: 'Mr. Nice' },
   { id: 2, name: 'Narco' },
   { id: 3, name: 'Bombasto' },
   { id: 4, name: 'Celeritas' },
   { id: 5, name: 'Magneta' },
   { id: 6, name: 'RubberMan' },
   { id: 7, name: 'Dynama' },
   { id: 8, name: 'Dr IQ' },
   { id: 9, name: 'Magma' },
   { id: 10, name: 'Tornado' }
];

hero.html

<h1>{{title}}</h1>
<h2>My Heroes</h2>
<ul class="heroes">
  <li *ngFor="let hero of heroes">
    <span class="badge">{{hero.id}}</span> {{hero.name}}
  </li>
</ul>
<h2>{{hero.name}} details!</h2>
<div>
    <label>id: </label>{{hero.id}}
</div>
<div>
    <label>name: </label>
    <input [(ngModel)]="selectedHero.name" placeholder="name">
<div>

다음은 사진입니다.

여기에 이미지 설명 입력


The variable selectedHero is null in the template so you cannot bind selectedHero.name as is. You need to use the elvis operator for this case:

<input [ngModel]="selectedHero?.name" (ngModelChange)="selectedHero.name = $event" />

The separation of the [(ngModel)] in [ngModel] and (ngModelChange) is also needed because you can't assign to an expression that uses the elvis operator.

I also think you mean to use:

<h2>{{selectedHero?.name}} details!</h2>

instead of:

<h2>{{hero.name}} details!</h2>

You just needed to read a little further and you would have been introduced to the *ngIf structural directive.

selectedHero.name doesn't exist yet because the user has yet to select a hero so it returns undefined.

<div *ngIf="selectedHero">
  <h2>{{selectedHero.name}} details!</h2>
  <div><label>id: </label>{{selectedHero.id}}</div>
  <div>
    <label>name: </label>
    <input [(ngModel)]="selectedHero.name" placeholder="name"/>
  </div>
</div>

The *ngIf directive keeps selectedHero off the DOM until it is selected and therefore becomes truthy.

This document helped me understand structural directives.


You were getting this error because you followed the poorly-written directions on the Heroes tutorial. I ran into the same thing.

Specifically, under the heading Display hero names in a template, it states:

To display the hero names in an unordered list, insert the following chunk of HTML below the title and above the hero details.

followed by this code block:

<h2>My Heroes</h2>
<ul class="heroes">
  <li>
    <!-- each hero goes here -->
  </li>
</ul>

It does not instruct you to replace the previous detail code, and it should. This is why we are left with:

<h2>{{hero.name}} details!</h2>

outside of our *ngFor.

However, if you scroll further down the page, you will encounter the following:

The template for displaying heroes should look like this:

<h2>My Heroes</h2>
<ul class="heroes">
  <li *ngFor="let hero of heroes">
    <span class="badge">{{hero.id}}</span> {{hero.name}}
  </li>
</ul>

Note the absence of the detail elements from previous efforts.

An error like this by the author can result in quite a wild goose-chase. Hopefully, this post helps others avoid that.


이를 방지하기 위해 selectedHero구성 요소 멤버를 정의되지 않은 상태로 두는 대신 빈 개체로 초기화 할 수도 있습니다.

예제 코드에서 다음과 같은 결과를 얻을 수 있습니다.

export class AppComponent {
  title = 'Tour of Heroes';
  heroes = HEROES;
  selectedHero:Hero = new Hero();

  onSelect(hero: Hero):void{
      this.selectedHero = hero;
  }
}

이 라인

<h2>{{hero.name}} details!</h2>

외부에 있으므로 실패 *ngFor가 없습니다 .herohero.name


이것은 나를 위해 일했습니다.

export class Hero{
   id: number;
   name: string;

   public Hero(i: number, n: string){
     this.id = 0;
     this.name = '';
   }
 }

그리고 초기화를 잘 선택했는지 확인하십시오.

selectedHero: Hero = new Hero();

참고 URL : https://stackoverflow.com/questions/39755336/angular2-cannot-read-property-name-of-undefined

반응형