Search code examples
angulardata-bindingangular8

how to pass data to the nested component in Angular 8?


In a parent html, I have many components such as chart 1,2,3,4,5. Then whenever I changed the date, I want to send the selected date to all the components. The code below is the implementation of the parent child event emitter. But I am getting no value from this html file when I check <kt-chart1> component? Also, I want to know when I get the data so I can sort chart by date by executing functions.

html

<!-- ----------------------------------------------------------------------- -->
<!--                            date range field                             -->
<!-- ----------------------------------------------------------------------- -->
<div class="row">
    <div class="col-xl-4">
        <mat-form-field class="flex-container">
            <div [formGroup]="form">
                <input
                    matInput
                    placeholder="Choose a date"
                    [satDatepicker]="picker2"
                    formControlName="date"
                    (dateChange)="DateChanged($event)"
                />
            </div>
            <sat-datepicker #picker2 [rangeMode]="true"> </sat-datepicker>
            <sat-datepicker-toggle
                matSuffix
                [for]="picker2"
            ></sat-datepicker-toggle>
        </mat-form-field>
        <div class="col-xl-6 chartPadding">
        <h4 class="text-center">Cost Per Tonne</h4>
        <kt-chart1 (sendingDateEmitter)="receivedDate($event)"></kt-chart1>
        <kt-chart2 (sendingDateEmitter)="receivedDate($event)"></kt-chart2>
        <kt-chart3 (sendingDateEmitter)="receivedDate($event)"></kt-chart3>

    </div>
    </div>
</div>


Typescript

    @Output() sendDateEmitter = new EventEmitter<any>();

    DateChanged($event) {
        this.sendDateEmitter.emit($event.value);

    }

Solution

  • To each of the charts add

    @Input() date: Date;
    

    And pass it to charts

    <kt-chart1 (sendingDateEmitter)="receivedDate($event)" [date]="form.get('date').value"></kt-chart1>
    <kt-chart2 (sendingDateEmitter)="receivedDate($event)" [date]="form.get('date').value"></kt-chart2>
    

    Make sure form is initialized before rendering, otherwise you might need to do something like [date]="form.get('date')?.value"

    To detect date changes in chart use OnChanges

    ngOnChanges(changes: SimpleChanges) {
      if (changes.date) {
        // Date has changed, do something with it.
      }
    }