send data from parent to child angular code example

Example 1: angular send data to parent component

import { Component, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'app-child',
  template: `
      <button (click)="sendMessage()">Send Message</button>
  `,
  styleUrls: ['./child.component.css']
})
export class ChildComponent {

  message: string = "Hola Mundo!"

  @Output() messageEvent = new EventEmitter<string>();

  constructor() { }

  sendMessage() {
    this.messageEvent.emit(this.message)
  }
}

Example 2: input property angular

//passing properties to child elements
<app-slider [title]="'This is a title'"> </app-slider>

//inside the component slider i add just before the constructor :
.
.
@input() title: string;
constructor(){
}


//after this we can use these new property inside the .html file of the component
<div id='slider' class='slider-big'>
  <h1> {{title}}</h1>

</div>

Example 3: how to pass variable via component after it's updated angular

// you can try like this, here you want to get the data from the parent component to child component, Here your parent component is ParentComponent and child component is app-child so here for getting the data from parent to child we can use ngOnChanges(changes: SimpleChanges)

// ParentComponent.html

<app-child
[data]="data"
(filterEmmiter)="filter($event)">
</app-child>
// child.component.ts


import {Component, OnChanges, SimpleChanges, Input} from '@angular/core';

class Child  implements OnInit, OnChanges {

    @Input() Data: any; // here is the data variable which we are getting from the parent 

    constructor() {}

    ngOnchanges(changes: SimpleChanges) {
      console.log(changes); // here you will get the data from parent once the input param is change
    }   

}

Tags: