Angular 从父组件访问子组件数据
我在子组件中有一个列表。我想从父组件(Angular 从父组件访问子组件数据,angular,viewchild,Angular,Viewchild,我在子组件中有一个列表。我想从父组件(AppComponent)访问此列表,并使用@ViewChild装饰器显示它,但该列表在父组件中始终未定义 导出类CategorieComponent实现OnInit{ @Output()listCategories:Categorie[]; 构造函数(专用http:HttpClient){ this.http.get('api/Categorie').subscribe(值=>{ this.listCategories=值; }); } 恩戈尼尼特(){
AppComponent
)访问此列表,并使用@ViewChild
装饰器显示它,但该列表在父组件中始终未定义
导出类CategorieComponent实现OnInit{
@Output()listCategories:Categorie[];
构造函数(专用http:HttpClient){
this.http.get('api/Categorie').subscribe(值=>{
this.listCategories=值;
});
}
恩戈尼尼特(){
}
}
app-component.ts
@ViewChild(分类组件,{static:false})
私有categoryComponent:categoryComponent;
.
.
.
ngAfterViewInit(){
this.listCategories=this.categoryComponent.listCategories;
}
app.component.html
{{cat.nomCat}}
不太清楚您在这里想做什么。但是由于在CategorieComponent
中需要一个AJAX调用,并且您希望了解AppComponent
中的数据检索成功情况,因此将listcegories
属性作为@Output
属性公开是有意义的
但随后您必须将其声明为ref的类型EventEmitter
不太清楚你想在这里做什么。但是由于在CategorieComponent
中需要一个AJAX调用,并且您希望了解AppComponent
中的数据检索成功情况,因此将listcegories
属性作为@Output
属性公开是有意义的
但随后您必须将其声明为ref的类型EventEmitter
您是否在父组件中使用了CategorieComponent
?您为什么不为此目的使用服务?是的,我是。父组件实际上是AppComponent
。我确信get调用会返回我需要的列表。我认为要获取数据,您应该使用服务,而不是组件。是否有必要使用组件?您是否在父组件中使用CategorieComponent
?以及为什么不使用服务?是的,我是。父组件实际上是AppComponent
。我确信get调用会返回我需要的列表。我认为要获取数据,您应该使用服务,而不是组件。是否有必要使用组件?如果应用程序类别不是AppComponent的直接子级,该怎么办?而应用程序类别实际上没有选择器?如何将该组件中的数据访问到AppComponent?如果应用程序类别不是AppComponent的直接子级,该怎么办?而应用程序类别实际上没有选择器?如何将该组件中的数据访问到AppComponent中?
import { Component, OnInit, Output, EventEmitter } from "@angular/core";
import { HttpClient } from "@angular/common/http";
import { Categorie } from "../categorie.model";
@Component({
selector: "app-categorie",
templateUrl: "./categorie.component.html",
styleUrls: ["./categorie.component.css"]
})
export class CategorieComponent implements OnInit {
@Output() listCategories: EventEmitter<Categorie[]> = new EventEmitter<Categorie[]>();
constructor(private http: HttpClient) {}
ngOnInit() {
this.http.get<Categorie[]>("/assets/categorie.json").subscribe(value => {
console.log(value);
this.listCategories.emit(value);
});
}
}
<app-categorie
(listCategories)="setListCategories($event)">
</app-categorie>
<select name="" id="" *ngIf="listCategories">
<option
*ngFor="let cat of listCategories"
[value]="cat.idCat"
[selected]="cat.idCat == projet.idCat">
{{cat.nomCat}}
</option>
</select>
listCategories: Array<Categorie>;
projet = { };
setListCategories(listCategories) {
console.log('listCategories:: ', listCategories);
this.listCategories = listCategories;
}