Angular 2+: Passing data between components (Quick Note)

Hi devs,

This is a quick note to guide you how to pass data between components. There are 2 main ways of doing this:
1. Passing data from Parent to Child
2. Passing data from Child to Parent

1. Passing data from Parent to Child - using @Input()

1.1. Add variable to child component to retrieve value

child.component.html
<p>Value from parent: {{parentValue}}</p>

child.component.ts
parentValue: string;
@Input() set valueFromParent(value: any){
this.parentValue = value;
};

1.2.  Pass value from parent to child

parent.component.html
<app-child [valueFromParent]="parentValue"></app-child>

parent.component.ts
export class ParentComponent implements OnInit {

parentValue: string = "sss";
constructor() { }

ngOnInit() {
}
}


2. Passing data from Child to Parent - using @Output() and EventEmitter

2.1. child.component.ts
@Output() valueForParent = new EventEmitter<string>();

ngOnInit() {
this.passDataToParent();
}

passDataToParent(){
this.valueForParent.emit("aaa");
}

2.2. parent.component.ts
childValue: string;

getValueFromChild(value: string){
this.childValue = value;
}

2.3. parent.component.html
<app-child [valueFromParent]="parentValue" (valueForParent)="getValueFromChild($event)"></app-child>
<p>Value from child: {{childValue}}</p>

Comments

Popular posts from this blog

Deploy Angular 8 app to Azure with Azure DevOps

Apache ActiveMQ 5 with .Net Core 3.1 and C#

Firebase with.Net Core and C#