Master-Child in Angular App
Hi Friends, This is Lakshman here.
As part of the Series "Angular Best Practices".
Today, We will Master-Child in Angular App.
Pre-requisites:
The pre-requisites are
- Node.JS - Click Here
- Angular CLI - Click Here
- VS Code - Click Here
Check this out
- To understand how to Structure your Angular App - click here
Master-Child
On every application, the master-child concept will exist because it's a traditional approach to flow data.
In Angular to implement it, we have two decorators,
- @Input
- @Output
These decorators will be declared only on the child component, where the master send input and receive output.
Such code will look like below,
//#region Input Variables
@Input() todo: Todo;
@Output() todosEvent = new EventEmitter<Todo[]>();
//#endregion
To Send and receive information from Master, use it like angular default properties as below,
<app-todo-entry [todo]="todo" (todosEvent)="rtnTodoList($event)"></app-todo-entry>
To Sent data from Child to Master, we need to Output decorator with Emit Option as below,
this.todosEvent.emit(todos);
When we pass the Item Info to Edit from Master to Child, you need to use one of the Angular Event called OnChange as below,
export class TodoEntryComponent implements OnInit, OnChanges {
//#region Input Variables
@Input() todo: Todo;
@Output() todosEvent = new EventEmitter<Todo[]>();
//#endregion
....
ngOnChanges(): void {
if (this.todo !== undefined && this.todo !== null) {
this.updateForm(this.todo);
} else {
this.resetForm();
}
}
...
}
That wraps up the Master-Child in Angular App
You may also access to source code on GitHub by Click Here
On-road head, we will discuss a lot of things.
Looking forward to your comments and share your feedback.
Until that, I am Lakshman, Signing Off.
Comments
Post a Comment