簡體   English   中英

具有來自父組件的屬性的 Angular 子組件

[英]Angular children components with attributes from parent component

我正在嘗試創建以下組件架構。 具有大模板的父組件,該模板是許多子組件的占位符。 父組件負責從服務器獲取數據。 父模塊還有一個服務來為子組件提供數據。 實際的數據訂閱發生在子組件中。 這是一些相關代碼:通用子組件:

import { Component, OnDestroy, OnInit, ViewChild, ElementRef, AfterViewInit } from '@angular/core';
import { DataSvcService } from '../../dashboard/data-svc.service';

@Component({
 selector: 'app-generalstatistics',
 templateUrl: './generalstatistics.component.html',
 styleUrls: ['./generalstatistics.component.css']
})
export class GeneralstatisticsComponent implements OnInit, OnDestroy, AfterViewInit  {
@ViewChild('generalstatistics', {static: false}) span: ElementRef;
subscription;
generalStatistics = new Array({});

constructor(private dataSvc: DataSvcService) {}

ngOnInit() {
  this.subscription = this.dataSvc.generalstatistics.subscribe(data => {
  this.generalStatistics = data;
 });
}
ngAfterViewInit() {
  console.log(this.span);
}
ngOnDestroy() {
  this.subscription.unsubscribe();
}
}

模板:generalstatistics.component.html

<span #generalstatistics></span>

父組件(實現模板):

<div class="card-body pb-0">
    <app-generalstatistics></app-generalstatistics>
</div>

父組件服務:'../../dashboard/data-svc.service'

import { BehaviorSubject, Subject, Observable } from 'rxjs';
import { Injectable } from '@angular/core';

@Injectable()
export class DataSvcService {

constructor() { }
  public generalstatistics = new BehaviorSubject<Array<object>>([{}]);

public get generalStatistics(): Observable<Array<object>> {
  return this.generalstatistics.asObservable();
}
}

父組件數據請求:

this.http.get<any>(`${environment.apiUrl}/api/
 home/`)
.subscribe((data: any) => {
  this.dataSvcService.generalstatistics.next(data);
});

我的想法是我希望將一般統計作為通用組件。 實際的數據綁定應該發生在父組件中。 我正在嘗試在實現中添加這樣的東西:

<app-generalstatistics **#someid**></app-generalstatistics>

所以我可以在generalstatistics組件代碼中識別它並將數據分配給span元素。 但是當我檢查 this.span.nativeElement 時,我沒有看到任何來自實際實現的東西。

我的問題是如何將數據綁定到我的解決方案中的子組件? Shuold我改變整個架構?

謝謝

你試過這個嗎? 在您的父組件中,您可以像這樣傳遞:

<app-generalstatistics [id]="someid" ></app-generalstatistics>

在您的 generalstatistics component.ts 中,您可以通過以下方式接收:

@Input() id;

讓我們假設您的服務正確地返回了您正在尋找的對象數組。 您需要做的就是將該數據綁定到您的子組件。

因此,在您的子組件中,它只會在ts文件中包含以下內容。

@Input() data: any; // You can replace "any" with an interface of the expected object

然后在你的父 html 文件中,如果你知道數據返回的順序,你可以靜態綁定數據,像這樣:

<app-generalstatistics
[data]="this.generalStatistics[0]"
>

<app-generalstatistics
[data]="this.generalStatistics[1]"
>

或者,如果您不確定數組中有多少對象,您可以簡單地指定:

<app-generalstatistics *ngFor="let gS of generalStatistics"
[data]="gS"
>

使用上述任何一種策略,您都可以刪除ViewChild()和 elementRef,因為您最終不會在ts文件中再次使用它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM