Malik Kashmiri
Malik Kashmiri

Reputation: 5861

Pass Model from one component to other in Angular 5

Problem

I am using angular 5 for SPA. I have 2 component Parent Child. I called an API from Parent component and cast the response of that API into Model. Now I want to pass that model into other component. I already use @Input to get the model but it render in the view but not catch into the component. when I console.log that model I passed it shows me undefined.

Code

import {Component, Inject, OnInit} from '@angular/core';
import {MAT_DIALOG_DATA, MatDialog} from "@angular/material";

import {SpecDetailsServ } from "../services/SpecDetailsServ";
import {SpecDetailsModel} from "../models/SpecDetailsModel";
import {Quote} from "../models/Quote";
import {ServiceDialogComp} from "./ServiceDialogComp";
import {QuoteDetailsDialogComp} from "./QuoteDetailsDialogComp";

@Component({
  selector: 'app-spec-details-comp',
  templateUrl: '../views/spec-details.html',
  styleUrls: ['../../assets/css/component.css']
})

export class SpecDetailsComp implements OnInit {
    customerId = 1;



    getSpecDetails: Array<SpecDetailsModel>;
    showLoader = true;
    getQuotes: Quote;

    constructor(private getspecdetails: SpecDetailsServ, private matdialog: MatDialog) {
        this.getspecdetails.getSpecDetails(1).subscribe(res => {
            var resNew:any = res;
            this.getSpecDetails = resNew.result;
            this.showLoader = false;
        })
    }

    ngOnInit() {}
}   

Parent View

<app-quote-details [getSpecDetails]="getSpecDetails"></app-quote-details>

Child Component

import {Component, Inject, OnInit, Input} from '@angular/core';
import {SpecDetailsComp} from "./SpecDetailsComp";
import {MAT_DIALOG_DATA, MatDialog} from "@angular/material";

@Component({
    selector: 'app-quote-details',
    templateUrl: '../views/quote-details.html',
    styleUrls: ['../../assets/css/component.css'],
})

export class QuoteDetailsDialogComp {

   //this is the model i wanna pass to other component with data init
    @Input() getSpecDetails: Array<SpecDetailsModel>;

    constructor() {
        console.log(this.message);
    }
}

Upvotes: 1

Views: 2113

Answers (2)

Arun
Arun

Reputation: 3841

The better solution is to add ngOnChanges angular lifecycle hook on child. This will update your child component whenever there are any changes in the input. using *ngIf is another solution but this will update only once -during initialization and changes wont be reflected. Check this link that explains it very easily.

Upvotes: 1

BeeBee8
BeeBee8

Reputation: 3074

Add *ngIf="getSpecDetails" to your child component.

Your child components init is happening before you get response from server.

When you add ngIf child component's init will trigger only after getSpecDetials? in defined.

Upvotes: 1

Related Questions