How do I achieve the following functionality: I want a child component to have an input field and a SEND button. When the button is clicked, the value entered in the input field should be displayed in the parent component.
This approach currently works: The child component's input field uses ngModel for two-way data binding. The SEND button triggers a function that adds the current input value to an array. The parent component utilizes ViewChild() to display each new value in the list using *ngFor loop.
Is there a way to accomplish this with just a single value variable instead of an array? The commented-out code (for array implementation) is functioning correctly. Check out the Stackblitz link for reference: Stackblitz
Your assistance on this matter would be greatly appreciated. Thank you.
Child Component
template:
<input type="text" [(ngModel)]="currentMsgToParent">
<button (click)="msgToParent()">send</button>
.ts:
export class Child1Component {
name = 'Child';
currentMsgToParent = '';
// msgFromChild1 = []
msgToParent() {
this.currentMsgToParent;
// this.msgFromChild1.push(this.currentMsgToParent);
}
}
parent component:
template:
<div class="child1">
<p><b>Message from Child</b><br> via ChildView():</p>
<p>{{ currentMsgToParent }}</p>
<!-- <ul *ngFor="let item of msgFromChild1">
<li>{{ item }}</li>
</ul> -->
<hr>
<app-child1></app-child1>
</div>
ts.:
export class AppComponent implements AfterViewInit {
@ViewChild(Child1Component, {static: false}) child1: Child1Component;
name = 'Parent';
msgFromChild1: any;
currentMsgToParent = '';
ngAfterViewInit() {
this.currentMsgToParent = this.child1.currentMsgToParent;
// this.msgFromChild1 = this.child1.msgFromChild1;
}
}