Tips for transferring the value of a text box between components bidirectionally in Angular 8

Let's create a scenario where we have two components: login and home. The goal is to capture the value entered in the text box of the login component and pass it to the text box in the home component when the "proceed" button in the login component is clicked. Similarly, we also want to capture the value from the home component's textbox and pass it back to the login component's textbox when the "proceed" button in the home component is clicked. Below is the code snippet for reference:

Login Component - login.component.html

<div>
<p>Parent Component</p>
<input type="text" [(ngModel)]="inptext">
</div><br>
<button (click)="proceed()">Proceed</button>

Login Component - login.component.ts

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router'; 
@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
  users:any;
  constructor(private router: Router) { }

  ngOnInit() {
 
  }
 proceed(){
     alert(this.inptext);
     this.router.navigateByUrl('/home');
 }
  
}

Home Component - home.component.html

<div>
<p>Child Component</p>
<input type="text" [(ngModel)]="inptext">
</div><br>
<button (click)="proceed()">Proceed</button>

Home Component - home.component.ts

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router'; 
@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
  getListData: boolean = false;
  constructor(private router: Router) { }

  ngOnInit() {

  }
 proceed(){
      
      alert(this.inptext);
       this.router.navigateByUrl('/');
 }
}

Answer №1

  1. Start by importing the home.component into the app.module.ts file and declaring it within the providers section.

  2. Next, import the home.component into the login.component file and inject the component in the constructor using public home: HomeComponent.

  3. You can then access all the variables and functions within the homeComponent by using this.home.variable_name.

This method allows you to assign the value of an input to a variable within the home component's function that is called in the onClick method.

Answer №2

To establish communication between components, you can utilize various methods within Angular:

  1. Utilize @output and @Input decorators for parent-child interactions.
  2. Implement a Shared Service.
  3. Use Observable to emit events.
  4. Incorporate State Management solutions like ngrx.

For detailed guidelines, refer to the official documentation on Component interaction

The choice between techniques #1 to #4 will vary based on factors such as your Application Scope and State Management Policy.

A straightforward approach involves defining a Shared Service with setter and getter methods that can be injected into both components.

Consider this example:

shared.model.ts

export interface IItem {
    name: string;
}

shared.service.ts

import { Injectable } from '@angular/core';
import { IItem } from '../entities/iItem';
 
@Injectable()
export class ModelService {
 
    private _items:IItem[] = [];
 
    addItem(item: IItem) {
        this._items.push(item);
    }
 
    getItems(): IItem[] {
        return this._items;
    }
}

Component.template.html

<div>
  <input [(ngModel)]="item.name" placeholder="Item name here..">
  <button (click)="addItem()">Add Item</button>
</div>

Component.component.ts

import { Component } from '@angular/core';
import { ModelService } from '../services/model.service';
import { IItem } from '../entities/iItem';
 
@Component({
  selector: 'create-item',
  templateUrl: './createitem.component.html'
})
export class CreateItemComponent {
 
  private _item:IItem = {name:'',description:'',price:0};
 
  constructor(private _modelService: ModelService){}
 
  public get Item():IItem{
     return this._item;
  }
 
  public addItem(){
     const currentItem:IItem = {
         name:this._item.name,
         description:this._item.description,
         price:this._item.price
     };
 
    this._modelService.addItem(currentItem);
  }
}

ViewComponent.template.html

<div>
  <button (click)="printItems()">Print Item</button>
</div>

ViewComponent.component.ts

import { Component } from '@angular/core';
import { ModelService } from '../services/model.service';
 
@Component({
  selector: 'view-items',
  templateUrl: './viewitems.component.html'
})
 
export class ViewItemsComponent {
 
constructor(private _modelService: ModelService){}
 
 public printItems(){
    console.log('items in warehouse:');
    console.log(this._modelService.getItems());
 }
 
}

For additional insights and explanations, check out this informative article at this link.

Answer №3

Utilize @input and shared service to easily achieve this:

//to-login-service.ts

@Injectable({providedIn: 'root'})
export class ToLoginService {
  private data: Subject<string> = new Subject<string>();

  sent(val: string) {
    this.data.next(val);
  }

  get(): Observable<string> {
    return this.data.asObservable();
  }
}

//login-component.ts

@Component({
selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
  inptext: string;
  passtoHome: string;
  getFromHome: string;

  constructor(private toLoginService: ToLoginService) { }

  ngOnInit() {
    this.toLoginService.get().subscribe(val => {
      this.getFromHome = val;
    });
  }

  proceed() {
    this.passtoHome = this.inptext;
  }
}

//login-component.html

<h2>Sent From Home(Child): {{getFromHome}}</h2>

<div>
  <p>Parent Component</p>
  <input type="text" [(ngModel)]="inptext">
</div><br>
<button (click)="proceed()">Proceed</button>


<hr/>

<app-home [pass-from-login]="passtoHome"></app-home>

//home-component.ts

@Component({
selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
  inptext: string;
  sentFromLogin: string;

  @Input('pass-from-login')
  set passFromLogin(val: string) {
    this.sentFromLogin = val;
  }

  constructor(private toLoginService: ToLoginService) { }

  ngOnInit() {
  }

  proceed() {
    this.toLoginService.sent(this.inptext);
  }
}

//home-component.html

<h2>Sent From Login (Parent): {{sentFromLogin}}</h2>
<div>
  <p>Child Component</p>
  <input type="text" [(ngModel)]="inptext">
</div><br>
<button (click)="proceed()">Proceed</button>

This setup will give you a view similar to the one shown here:

https://i.sstatic.net/3o3bI.png

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with router navigation not functioning within an output event in Angular 4

I've encountered a situation with my table component where it emits an event containing an id. `@Output() onClick: EventEmitter<any> = new EventEmitter<any>();` `onRowClick(id: any) { this.onClick.emit(id); }` `<a href="#" (click ...

Struggling with parsing JSON in TypeScript/React because of type issues

Upon receiving an API response, I would like to parse the data since it is in the form of an array of objects. Here's an example of how the JSON looks: { "totalSize": "56", "sortedKeys": [ { & ...

Adding dropdowns to divs in Angular applications

Currently, I am attempting to integrate a dropdown feature into a div element. The HTML code for the dropdown is generated dynamically within the code. When clicking on the dropdown button, it appears functional but unfortunately, the dropdown itself does ...

What is the process for connecting a date/time form control?

My code seems to only be working for the 'title' element, while the 'docdatetime' control remains blank. Can anyone spot what I'm doing wrong? //template =================================================== <div class="form-grou ...

Angular navigation system featuring hierarchical categories

My goal is to organize categories in a nest structure, but without setting a predetermined limit on the number of levels. Depending on various factors, there could be anywhere from 3 to 5 levels. For example, level 1 could be "categoryX/1", level 2 "categ ...

Exploring the Functionality of HTML Anchor Link Fragment within Angular 6

I've been working on an Angular 6 project where I've disabled the hash-location-strategy, removing # from the URL. As a result of this change, a link like: <li routerLinkActive="active"> <a [routerLink]="['/settin ...

Incorporating Azure blob image URLs within an Angular project

I have an ASP.NET WEB API and an angular project. I am considering using Azure blob storage to store and retrieve image files for displaying to users. Is it best practice to fetch the image URL from the API, transmit it to the client-side, and then use t ...

Tips for accessing a specific ListItem within the Menu Component using MUI for React

Within my code, I am working with a List that contains multiple ListItems pulled from an array called myCollection. Each ListItem has a MenuIcon element which triggers a menu to appear, providing the option to delete the specific item. Here is a simplified ...

conflict between ng-content and textarea elements

My custom component called my-textarea has a unique template structure: <textarea> <ng-content></ng-content> </textarea> However, when I try to input text into the component using the same method as a regular textarea HTML eleme ...

When you find that the plugins on pub.dev do not offer web support, consider utilizing npm packages for Flutter web development

I am currently working on developing a cross-platform app using Flutter for iOS, Android, and web. However, some plugins do not support web. Fortunately, I came across npm packages that provide the same functionality and I am considering integrating them. ...

significant issue arising from slow input box typing in angular 5 causing concern

We've encountered a troublesome issue that is hindering our progress despite completing a web app using angular 5 & template driven forms. Everything works flawlessly except for one feature causing major disruption, like a sniper shot hitting us unexp ...

Send out data every 250 milliseconds in a way that resembles debounceTime(), but without any waiting period

When the window is resized, I have a complex operation that rearranges multiple DOM elements. To prevent frequent updates, I implemented debounceTime(250ms) to introduce a delay before refreshing the components. However, this approach can cause issues if ...

Tips for incorporating a child's cleaning tasks into the parent component

I am working with a parent and a child component in my project. The parent component functions as a page, while the child component needs to perform some cleanup tasks related to the database. My expectation is that when I close the parent page/component, ...

Move your cursor over a div element while utilizing NgClass

I'm currently working on implementing a hover effect on a div using an Angular ngClass directive. Within the template file, I have a div element with the class "list-item-container" that includes another div with the class "list-item." This "list-item ...

A guide to creating a TypeScript redux middleware class

As specified in the typescript definition for Redux, these interfaces must be implemented to create middleware: /* middleware */ export interface MiddlewareAPI<D extends Dispatch = Dispatch, S = any> { dispatch: D getState(): S } /** * A midd ...

When attempting to retrieve and process a JSON from the internet, I encounter "undefined" errors despite the fact that the data appears correctly in the log

I'm having trouble processing the JSON data received from a server. When I attempt to use .forEach on it, I receive an error stating that the data is undefined even though the console.log shows the correct values. What could be causing this issue? Is ...

Creating an RxJS observable stream from an event emitted by a child element in an Angular 2 component template

Currently incorporating Angular 2.0.0-rc.4 alongside RxJS 5.0.0-beta.6. In the midst of exploring various methods for generating observable streams from events, I find myself inundated with choices and would like to gather opinions. Recognizing that there ...

The class variable cannot access the Angular Http response returned by the service

I have a Typescript application built with Angular 2. In this application, I need to retrieve Build Artifacts from a Jenkins server using the Jenkins Rest API. The Build Artifact contains a text file that I want to read from. I am making use of Angular&apo ...

What sets apart "activate" from "ngOnInit"?

I came across this example on the Angular 2 Style Guide website. In my implementation, I would invoke this.show(); within the ngOnInit method, whereas in the demonstration it is called in the activate method. Could someone please explain the distinction ...

What is the best way to implement a subquery using EXISTS in Knex?

I'm currently facing challenges while constructing a query using knex, specifically when it comes to incorporating the 'WHERE' clause with the condition EXISTS (SELECT * FROM caregiver_patient WHERE patient_id IN (0,1)). Below is the origin ...