我有3个组成部分,1个父母和2个兄弟姐妹。我想将数据从子级1传递给父级,然后传递给子级2。
子项1-从JSON文件获取数据并将其呈现在列表中。然后,当单击列表项时,它会触发一个传递其数据的函数。
HTML
<li *ngFor="let data of data$ | async" (click)="projectSelect(data)">
<div class="listIcon {{data.id}}"></div>
<p>{{data.title}}</p>
</li>
TS
import { FetchDataService } from './../fetch-data.service';
import { Component, Renderer2, ElementRef, OnInit, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'project-navigation',
templateUrl: './project-navigation.component.html',
styleUrls: ['./project-navigation.component.scss']
})
export class ProjectNavigationComponent implements OnInit {
constructor(private renderer: Renderer2, private el: ElementRef, private FetchDataService: FetchDataService) { }
ngOnInit() { this.fetchProjects() }
data$;
@Output() projectSelectEvent = new EventEmitter<Event>();
fetchProjects() {
this.data$ = this.FetchDataService.fetchProjects();
}
projectSelect(data: Event): void {
this.projectSelectEvent.emit(data);
}
}
App.Component-捕获数据
HTML
<div class="content">
<project-navigation (projectSelectEvent)="childProjectSelect($data)"></project-navigation>
<project-overview></project-overview>
</div>
TS
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
title = 'journal';
public clickedProject: Event;
constructor() { }
childProjectSelect(data: Event) {
console.log(data);
}
}
如果我console.log Child 1,我得到了我想要的数据,这会给我一个“ undefined”。我在做什么错了?
答案 0 :(得分:0)
如评论中所述,您只需要对app.component.html作一个小改动
(projectSelectEvent)="childProjectSelect($event)" change $data =>$event