angular - 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
解决方案
使用 ngOnChanges 检查输入值是否设置
ngOnChanges() {
if(!this.hero) return null;
this.i = this.hero.name
this.getHeroes();
}
推荐阅读
- c# - 无法使用 Linq 访问特定的 XML 文件块
- spring-mvc - Thymeleaf 布局装饰器不起作用
- c# - 多线程和位图使用
- cordova - 带有cordova的Phonegap App,无法安装插件
- javascript - 关闭应用程序时如何根据推送通知更新 UI(React Native)
- traffic - 如何从 mininet 中的跟踪文件生成流量?
- cordova - 离子项目中的cordova-plugin-file-downloader插件如何?
- python - word2Vec 和缩写
- azure-logic-apps - 如何从 Azure Functions 在 Azure Logic App Workflow 中动态添加 SFTP 文件路径
- angular - 如何在不使用 ngbTooltip 的情况下在 Angular 4 应用程序中实现 bootstrap 4 工具提示?