首页 > 解决方案 > Angular @Input() 没有绑定并且在 Angular 7 中不起作用

问题描述

我有一个带有这样组件的主模板:

   <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>]

Master组件是这样的:

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>]

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

错误类型错误:无法在 checkAndUpdateDirectiveInline 处读取 HeroDetailComponent.push../src/app/hero-detail/hero-detail.component.ts.HeroDetailComponent.ngOnInit (hero-detail.component.ts:19) 处未定义的属性“名称” (core.js:22099) 在 checkAndUpdateNodeInline (core.js:23363) 在 checkAndUpdateNode (core.js:23325) 在 debugCheckAndUpdateNode (core.js:23959) 在 debugCheckDirectivesFn (core.js:23919) 在 Object.eval [as updateDirectives ] (HeroesComponent.html:10) 在 Object.debugUpdateDirectives [as 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 

标签: angularangular7

解决方案


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

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

    this.getHeroes();

  }

推荐阅读