
In this example, what we want to update is pass a default value of name from parent to child
parent.component.ts import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-parent',
templateUrl: './parent.component.html',
styleUrls: ['./parent.component.css']
})
export class ParentComponent implements OnInit {
name = "John Doe"
constructor() { }
ngOnInit() {
}
}
parent.component.html <h2>Parent Component</h2>
<div style="border: 1px solid black;">
<app-child [nameFromParent]="name"></app-child>
</div>
child.component.ts import { Component, Input, OnInit } from '@angular/core';
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {
@Input() nameFromParent = ""
constructor() { }
ngOnInit() {
}
}
In the above code, we use the @Input() decorator. This allows the parent to update the child depending on the data passed to it. By default, as you can see, @Input() nameFromParent has empty string value. During code runtime, this will be supplied based from the data that parent has. In our case, the name variable from parent.
child.component.html <h3>I'm Child Component</h3>
<p>{{nameFromParent}}</p>
In this scenario, what we want is to send a data from child to parent. For example, if a user clicks the button on a child component, then update the default name on the parent component.
child.component.html <h3>I'm Child Component</h3>
<p>{{nameFromParent}}</p>
<button (click)="updateParentName()">Update name</button>
child.component.ts import { Component, Input, OnInit, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {
@Input() nameFromParent = ""
@Output() updateNameFromChild = new EventEmitter()
constructor() { }
ngOnInit() {
}
updateParentName() {
this.updateNameFromChild.emit('John Doe Jr.')
}
}
Here, we use the @Output() decorator and instantiate an EventEmitter. Basically, we want to throw an event from child to parent. When parent detects an event from the child, then the parent will call a local event inside that component to able to update the selected variable. In our case, it's the name. You can see the updated code of parent component below.
parent.component.html <h2>Parent Component</h2>
{{name}}
<div style="border: 1px solid black;">
<app-child (updateNameFromChild)="updateName($event)" [nameFromParent]="name"></app-child>
</div>
parent.component.ts import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-parent',
templateUrl: './parent.component.html',
styleUrls: ['./parent.component.css']
})
export class ParentComponent implements OnInit {
name = "John Doe"
constructor() { }
ngOnInit() {
}
updateName(e: any) {
this.name = e
}
}

That's it for the part 1.