Angular @Input()未绑定且在Angular 7中不起作用

时间:2019-05-29 05:55:21

标签: angular angular7

我有一个主模板,其组件如下:

   <h2>My Heroes</h2>
<ul class="heroes">
  <li *ngFor="let hero of heroes"
    [class.selected]="hero === selectedHero"
    (click)="onSelect(hero)">
    <span class="badge">{{hero.id}}</span> {{hero.name}}
  </li>
</ul>

<app-hero-detail [hero]="selectedHero"></app-hero-detail>]

主组件是这样的:

import { Component, OnInit } from '@angular/core';

import { Hero } from '../hero';
import { HeroService } from '../hero.service';

@Component({
  selector: 'app-heroes',
  templateUrl: './heroes.component.html',
  styleUrls: ['./heroes.component.css']
})
export class HeroesComponent implements OnInit {

  public selectedHero: Hero;

  heroes: Hero[];

  constructor(private heroService: HeroService) { }

  ngOnInit() {
    this.getHeroes();
  }

  onSelect(hero: Hero): void {

    this.selectedHero = hero;
  }

  getHeroes(): void {
    this.heroService.getHeroes()
        .subscribe(heroes => this.heroes = heroes);
  }
}

主模板正在从服务获取数据。

在列表中单击母版元素时,将显示“子级”详细信息。

在母版中使用此

 <li *ngFor="let hero of heroes"
[class.selected]="hero === selectedHero"
(click)="onSelect(hero)">

并绑定到

<app-hero-detail [hero]="selectedHero"></app-hero-detail>]

但是我在控制台中收到此错误。

  

错误TypeError:无法读取未定义的属性“名称”       在HeroDetailComponent.push ../ src / app / hero-detail / hero-detail.component.ts.HeroDetailComponent.ngOnInit中   (hero-detail.component.ts:19)       在checkAndUpdateDirectiveInline(core.js:22099)       在checkAndUpdateNodeInline(core.js:23363)       在checkAndUpdateNode(core.js:23325)       在debugCheckAndUpdateNode(core.js:23959)       在debugCheckDirectivesFn(core.js:23919)       在Object.eval [作为updateDirectives](HeroesComponent.html:10)       在Object.debugUpdateDirectives [作为updateDirectives](core.js:23911)       在checkAndUpdateView(core.js:23307)       在callViewAction(core.js:23548)

我的子组件是这样的:

import { Component, OnInit, Input } from '@angular/core';
import { Hero } from '../hero';
import { HeroService } from '../hero.service';

@Component({
  selector: 'app-hero-detail',
  templateUrl: './hero-detail.component.html',
  styleUrls: ['./hero-detail.component.css']
})
export class HeroDetailComponent implements OnInit {

  @Input() hero: Hero;

  heroes: Hero[];

  constructor(private heroService: HeroService) {  }
  i: string;
  ngOnInit() {
    this.i = this.hero.name

    this.getHeroes();

  }
  getHeroes(): void {

    this.heroService.getHeroes(this.i)
      .subscribe(heroes => this.heroes = heroes);
  }

}

请注意:我正在使用以下内容进行绑定:

@Input() hero: Hero; // in child component to parent template 

2 个答案:

答案 0 :(得分:2)

使用ngOnChanges检查是否设置了输入值

  ngOnChanges() {
    if(!this.hero) return null;
    this.i = this.hero.name

    this.getHeroes();

  }

答案 1 :(得分:0)

onInit中,hero可能没有定义,在初始化组件后会填充它。您可以尝试使用

@Input() set hero (value) {
   if(value) {
      this.i = this.hero.name;
   }
}