onmyway
onmyway

Reputation: 1505

Pass data from Parent Component to nested Child Component in Angular

I am having difficulties understanding how to make data available between Angular components. I have read up on @Input and @Output, but I am not sure whether this is what I need to use, and if so, how.

I have a parent component (an Asset with unique assetId), with a nested (child) component that should list all the documents related to the specific asset, based upon the assetId.

How can I pass the assetId from the asset component to the document component to use for fetching the required data for the specific record?

Upvotes: 1

Views: 1305

Answers (1)

Chrillewoodz
Chrillewoodz

Reputation: 28318

Template solution:

asset.component.ts:

@Input() assetId: string;

Usage of asset:

<asset assetId="x"></asset>

document.component.ts:

@Input() assetId: string;

asset.component.html:

<document [assetId]="assetId"></document>

Basically it just passes down the assetId to document which resides in asset's template.

EDIT

Component only solution:

export class AssetComponent {
  @ViewChild(DocumentComponent) document: DocumentComponent;
  @Input() set assetId(assetId) {
    this._assetId = assetId;
    this.document.assetId = assetId;
  } 

  get assetId() {
    return this._assetId;
  }

  private _assetId: string;
}

Here you pick up the DocumentComponent via ViewChild and access its assetId property via the document instance. Make sure that assetId in DocumentComponent is public.

Upvotes: 1

Related Questions