我在子组件中有一个列表。我想从父组件(AppComponent
)访问此列表,并使用@ViewChild
装饰器将其显示,但是该列表在父组件中始终未定义
export class CategorieComponent implements OnInit {
@Output() listCategories: Categorie[];
constructor(private http: HttpClient) {
this.http.get<Categorie[]>('api/Categorie').subscribe(value => {
this.listCategories = value;
});
}
ngOnInit() {
}
}
app-component.ts
@ViewChild(CategorieComponent, { static: false })
private categoryComponent: CategorieComponent;
.
.
.
ngAfterViewInit() {
this.listCategories = this.categoryComponent.listCategories;
}
app.component.html
<option *ngFor="let cat of listCategories" [value]="cat.idCat" [selected]="cat.idCat == projet.idCat">
{{cat.nomCat}}
</option>
答案 0 :(得分:2)
不太确定您要在这里做什么。但是,由于CategorieComponent
中需要进行AJAX调用,并且您想了解有关AppComponent
中数据检索成功的信息,因此将listCategories
属性公开为{{ 1}}属性。
但是您必须将其声明为@Output
类型。像这样:
EventEmitter<Array<Categorie>>
在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);
});
}
}
中,我不确定您为什么使用AppComponent
。您只需要调用一个处理ViewChild
listCategories
事件的方法。像这样:
@Output
然后您可以像这样定义<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>
方法:
setListCategories
这是您推荐的Sample Working Code。