在下面的代码中,我有选择英雄的方法,它正在更新app.component的selectedHero,但是在更新detail.component之后不会重新呈现。 请让我知道当父数据更改时如何通知子组件。
app.component.ts
import { heroes } from './Hero.service';
import { Component, OnInit } from '@angular/core';
import {Hero} from './Hero'
import { heroes } from './Hero.service';
import { Component, OnInit } from '@angular/core';
import {Hero} from './Hero'
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
title = 'tour-of-heroes';
Heroes:Hero[]=heroes;
selectedHero:Hero;
constructor(){
}
selectHero(hero){
this.selectedHero=hero;
console.log(this.selectedHero)
}
}
**主组件**
import { Hero } from './../Hero';
import { Component, OnInit ,Input, Output} from '@angular/core';
import { EventEmitter } from 'protractor';
@Component({
selector: 'app-master',
templateUrl: './master.component.html',
styleUrls: ['./master.component.scss']
})
export class MasterComponent implements OnInit {
@Input() Heroes:Hero[];
@Input() selectHero;
constructor() { }
ngOnInit() {
console.log(this.Heroes,'master Heroes')
}
}
details.component.ts
import { Hero } from './../Hero';
import { Component, OnInit, Input } from '@angular/core';
@Component({
selector: 'app-detail',
templateUrl: './detail.component.html',
styleUrls: ['./detail.component.scss']
})
export class DetailComponent implements OnInit {
@Input() selectedHero:Hero;
constructor() { }
ngOnInit() {
console.log(this.selectedHero)
}
}
**app.component.html**
'''
<div style="text-align:center">
<h1>Tour of Heroes</h1>
<div class="Layout">
<app-master [Heroes]="Heroes" [selectHero]="selectHero"></app-master>
</div>
<div class="Layout">
<app-detail [selectedHero]="selectedHero"></app-detail>
</div>
</div> '''
**master.component.html**
'''<div class="master">
<ul>
<li *ngFor="let hero of Heroes" (click)="selectHero(hero)">
<span>
Id : {{hero.id}}
</span>
<br/>
<span>
Name : {{hero.name}}
</span>
</li>
</ul>
</div>'''
** detail Component **
'''
<div *ngIf="selectedHero">
<h3>Selected Hero is : {{selectedHero.name}} </h3>
<div>
<p>Id : {{selectedHero.id}}</p>
<p>Name : {{selectedHero.name}}</p>
</div>
</div>
在app.complementent中,将英雄传递到details-component。
答案 0 :(得分:2)
在DetailComponent中,来自父组件的数据更改将在ngOnChanges生命周期挂钩上处理。
export class DetailComponent implements OnInit, OnChanges {
@Input() selectedHero:Hero;
constructor() { }
ngOnInit() {
console.log(this.selectedHero)
}
ngOnChanges() {
console.log(this.selectedHero)
}
}