【问题标题】:Access child component data from parent component从父组件访问子组件数据
【发布时间】:2020-04-14 02:17:24
【问题描述】:

我在子组件中有一个列表。我想从父组件(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() {

    }
}

应用组件.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>

【问题讨论】:

  • 你在父组件中使用CategorieComponent吗?
  • 还有为什么您不为此目的使用服务?
  • 是的,我是。父组件实际上是AppComponent。而且我确信 get 调用会返回我需要的列表
  • 我认为要获取数据,您应该使用服务,而不是组件。
  • 一定要使用组件吗?

标签: angular viewchild


【解决方案1】:

不太清楚你想在这里做什么。但由于 CategorieComponent 中需要 AJAX 调用,并且您想了解 AppComponent 中的数据检索成功,因此将 listCategories 属性公开为 @Output 属性是有意义的。

但是您必须将其声明为EventEmitter&lt;Array&lt;Categorie&gt;&gt; 类型。像这样的:

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 方法:

listCategories: Array<Categorie>;
projet = { };

setListCategories(listCategories) {
  console.log('listCategories:: ', listCategories);
  this.listCategories = listCategories;
}

这里有一个Sample Working Code 供您参考。

【讨论】:

  • 如果 app-categories 不是 AppComponent 的直接子级怎么办?并且应用程序类别实际上没有选择器?您如何从该组件访问数据到 AppComponent 中?
猜你喜欢
  • 2017-03-17
  • 1970-01-01
  • 2018-07-20
  • 1970-01-01
  • 2016-05-29
  • 2023-01-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多