父组件:
@Component({
selector: 'app-tripCreation',
templateUrl:
' <app-location (sendLocationDataEvent)="getLocationData($event)"></app-location>
<app-tripInfo [locationDetails]="locationData"></app-tripInfo> '
styleUrls: ['./tripCreation.component.scss']
})
export class TripCreationComponent{
locationData = {};
getLocationData(response: any)
{
this.locationData = response
console.log(this.locationData); // {pickAddressName: "KARWAN BAZAR, TEJGAON, DHAKA CITY", pickAreaID: 346, pickUnionID: 8195, pickThanaID: 512, …}
}
}
第一个子组件:
@Component({
selector: 'app-location',
templateUrl:
'<button type="button" class="btn" id = "set" (click)="setData()" >setData</button>',
styleUrls: ['./location.component.scss']
})
export class LocationComponent{
locationDetails: any = {};
@Output() sendLocationDataEvent = new EventEmitter<any>();
setData(){
this.locationDetails.pickAddressName = "KARWAN BAZAR, TEJGAON, DHAKA CITY";
this.locationDetails.pickAreaID = 346;
this.locationDetails.pickUnionID = 8195;
this.locationDetails.pickThanaID = 512;
this.sendLocationDataEvent.emit(this.locationDetails);
}
}
第二个子组件:
@Component({
selector: 'app-tripInfo',
templateUrl:
'<div *ngIf="pickLocation">
<p><span>pick location is: {{pickLocation}}</span></p> //pick location is:
</div>',
styleUrls: ['./tripInfo.component.scss']
})
export class TripInfoComponent{
@Input() public locationDetails: any = {};
pickLocation: srting = " ";
constructor()
{
console.log(this.locationDetails); // {} -> a blank object
this.pickLocation = this.locationData.pickAddressName;
}
}
[从第一个子组件中,我将对象类型的数据发送到父组件。然后我再次将数据从父级传递到第二个子级组件。父级正在获取数据对象并将其完美记录。但是第二个组件是记录一个空白对象。我不明白我在哪里错过比赛?
您必须对第二个子组件上的OnChanges
事件做出这样的反应:
export class TripInfoComponent implements OnChanges {
@Input() public locationDetails: any = {};
pickLocation: srting = " ";
constructor() { }
ngOnChanges (changes: SimpleChanges) {
console.log(changes.locationDetails);
this.pickLocation = changes.locationDetails.currentValue;
}
}