Skip to main content

Component Interaction

Previous article reminder

In Angular, the interaction between components (parent-to-child and child-to-parent) is usually implemented through Input and Output decorators. The following is the specific implementation of parent-to-child and child-to-parent in Angular:

@Input

Parent component passes data to child component

//Parent component front end
<app-son [name]="'Hoo'"></app-hello>

//Child component back end
import { Component, Input } from '@angular/core';

@Component({
selector: 'app-child',
template: `<p>{{ message }}</p>`
})
export class ChildComponent {
@Input() name: string = ''; // Use @Input to receive data passed by the parent component
}

@Output

The parent component passes an event to the child component, and the child component triggers the event through @output ejection

//Parent component
<app-son (addList)="addListFunction($event)"></app-hello>
//Parent component backend
list:Array<string> = ['Angular']
addListFunction(str:string){
this.list?.push(str)
}
//Child component backend
import { Component, Output, EventEmitter } from '@angular/core';

@output() addList = new EventEmitter()
addBtnFun(){
this.addList.emit('vue')
}

@ViewChild()

Get the attributes of an element, call methods of child elements, etc. The purpose of @ViewChild() is to allow you to reference elements in the template in the component class and interact with them.

//Parent component front-end
<app-son #mychild [name]="'Hoo'"></app-hello>
<button (click)="addFun()">Method to get child component</button>
//Parent component back-end
import { Component, ViewChild } from '@angular/core';

@VIewChild('mychild') child: any;
list:Array<string> = ['Angular']
addFun(){
this.child.addBtnFun()
}
//Child component back-end
import { Component, Output, EventEmitter } from '@angular/core';

@output() addList = new EventEmitter()
addBtnFun(){
this.addList.emit('vue')
}

Summary

  • Parent to child: Use @Input decorator, pass the data of the parent component to the child component.
  • Child to parent: Use @Output decorator and EventEmitter, the child component triggers the event, and the parent component listens and processes the passed data.