Connect ngModel value between multiple components

If you have a file named about.component.ts, it would contain the following code:

import { Component } from '@angular/core';

@Component({
  selector: 'about-section',
  template: `
    <input [(ngModel)]="name" placeholder="First Name">
    <p>{{name || 'user'}}</p>
  ` 
})

export class AboutComponent {

}

In addition to that, there is another file called notes.component.ts:

import { Component } from '@angular/core';

@Component({
  selector: 'notes-section',
  template: `
    <p>{{name || 'user'}}</p>
  ` 
})

export class NotesComponent {

}

These two files are components of yet another file named app.component.ts:

import { Component } from '@angular/core';

import { AboutComponent } from './about.component';
import { NotesComponent } from './notes.component';

@Component({
  selector: 'my-app',
  template: `
  <about-section></about-section>
  <notes-section></notes-section>
  `,
  directives: [AboutComponent, NotesComponent]
})

export class AppComponent { }

Moving on to my question, what would be the approach to bind the ngModel 'name' property from the about.component.ts file to the notes.component.ts file? This means that any changes made to the name property in one component should also reflect in the other component.

Answer №1

Here's one method to achieve it using the EventEmitter:

@Component({
  selector: 'about-section',
  template: `
    <input [ngModel]="name" (ngModelChange)="name = $event; modelChanged.emit($event)">
    <p>{{name || 'user'}}</p>
  ` 
})
export class AboutComponent {
  @Output() modelChanged = new EventEmitter();
}

@Component({
  selector: 'notes-section',
  template: `<p>{{name || 'user'}}</p>` 
})
export class NotesComponent {}

@Component({
  selector: 'my-app',
  template: `
   <about-section (modelChanged)="notes.name = $event"></about-section>
   <notes-section #notes></notes-section>`,
  directives: [AboutComponent, NotesComponent]
})
export class AppComponent { }

Visit this demo plunker link for more information.

To begin with, I used the banana in a box syntax [(ngModel)]="name" (https://angular.io/docs/ts/latest/guide/template-syntax.html#!#two-way-binding-with-ngmodel) to emit an event using the EventEmitter from the component where the ngModel is present.

<input [ngModel]="name" (ngModelChange)="name = $event; modelChanged.emit($event)">

Subsequently, I subscribed to this event in the parent component:

<about-section (modelChanged)="notes.name = $event"></about-section>

However, before that, I created a reference to another component to be able to modify the value of name, as shown in the code snippet above: notes.name = $event. Here, $event represents the "payload" of the emitted event, which in this case is the value inputted.

<notes-section #notes></notes-section>

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

Employing the forEach method on an array to search for a specific string and subsequently retrieve a function

I'm currently working on implementing a discount code system using AngularJS. I've defined a function called $scope.pricetotal that represents a specific value, an input field to capture a string, and an array. Here's the main objective: I w ...

Having issues with regEX functionality in an Angular form

I need to validate a phone number using regEX. My criteria is as follows: 10 digits alpha/numeric, where an Alpha CHAR is in the 4th position (excluding hyphens). For example: 586R410056  NNN ANN NNNN  (NNN) ANN NNNN  NNN-ANN-NNNN  (NNN) AN ...

Step-by-step guide on incorporating an external JavaScript library into an Ionic 3 TypeScript project

As part of a project, I am tasked with creating a custom thermostat app. While I initially wanted to use Ionic for this task, I encountered some difficulty in integrating the provided API into my project. The API.js file contains all the necessary function ...

Encountering an issue with resolving parameters for the DecimalPipe in ngBootstrap/Angular2

Just delving into the world of Angular2 and trying to learn through hands-on experience. However, I've hit a roadblock! I attempted to import ng-bootstrap and encountered this error: https://i.stack.imgur.com/QDVJ3.png Here's my systemjs.config ...

Making calls to an Angular GRPC API through an Envoy proxy

Having trouble connecting to the GRPC server from the UI via Envoy. Here's the code snippet for the Envoy proxy: static_resources: listeners: - address: socket_address: address: 0.0.0.0 port_value: 8888 filter_chains: ...

Enhancing Angular2 authentication with Auth0 for enabling Cross-Origin Resource Sharing

I have been working on implementing user authentication through Auth0. I followed the instructions provided on their website, but I am encountering authentication issues. Whenever I try to authenticate, an error message appears in the console stating that ...

Utilize AngularJS to modify the appearance of text

Just starting out with AngularJS and I need to achieve the following task. I have a text that says "bob" and two buttons, one for bold and one for italic. When the bold button is clicked, I want to make the text BOB bold and when the italic button is click ...

Where can I find the Cypress.json file for Angular integration with Cypress using Cucumber?

We are currently transitioning from Protractor to Cypress utilizing Cucumber with the help of cypress-cucumber-preprocessor. While searching for Angular documentation on this setup, including resources like , all references lead to an automatically generat ...

What could be the reason for Angular 2 not recognizing this valid regex pattern?

The regular expression shown below is considered valid (check here): ^(\+27|27|0)\s?(\d{2})[-\s]?(\d{3})[-\s]?(\d{4})$ Despite its validity, Angular 2 throws the following error: EXCEPTION: Error in ./App class App - i ...

Navigational assistance on the keyboard - Improving Accessibility

My situation involves selecting an option from a dropdown menu on X-page, which triggers the opening of Modal-1 while disabling the background. If a selection is made within Modal-1, it leads to Modal-2. I am facing two issues/questions: Upon opening Moda ...

retrieve document data from firestore using the service

Is there a way to get real-time data from a Firestore document using a service? According to Firebase's documentation, you can achieve this by following this link: https://firebase.google.com/docs/firestore/query-data/listen?hl=es#web-modular-api I ...

AngularJS checkbox validation requires a minimum of two checkboxes to be selected

When using AngularJS, I am looking to create a validation rule where a minimum of 2 checkboxes must be checked for the input to be considered valid. Here is what I have attempted: <div ng-repeat="item in items"> <label><input type="chec ...

Retrieve information from Angular service's HTTP response

Calling all Angular/Javascript aficionados! I need some help with a service that makes API calls to fetch data: app.service("GetDivision", ["$http", function($http){ this.division = function(divisionNumber){ $http.post("/api/division", {division:di ...

Tips for adding elements to an angular $scope.array?

Currently, I am facing an issue that I cannot seem to pinpoint (most likely due to my limited expertise in AngularJS). In my HTML file, I have a basic ng-repeat set up like this: <ul> <li ng-repeat="fot in fotografia"><img src="{{fot.path ...

unable to submit form using angular and express

I am encountering an issue with a post request in AngularJS to express. The HTML form on the client side is defined as follows: <div ng-controller="LoginCtrl"> <form ng-submit="login()"> <div> <label>Username</lab ...

Automatically selecting the country phone code based on the country dropdown selection

When the country dropdown is changed, I want the corresponding phone code dropdown to be dynamically loaded. <div class="row"> <div class="col-sm-8 col-md-7 col-lg-6 col-xl-5 pr-0"> <div class="form-group py-2"> <l ...

Ordering dates by week in AngularJS 1

Currently, I have a list of objects: [{ name: one, date: 2017-09-18 }, { name: two, date: 2017-09-11 }, { name: three, date: 2017-09-13 }] I am looking to organize this list by week. Perhaps like the following structure: { 1week(or , m ...

Having trouble getting a constructor to function properly when passing a parameter in

Here's the code snippet I'm working with: import {Component, OnInit} from '@angular/core'; import {FirebaseListObservable, FirebaseObjectObservable, AngularFireDatabase} from 'angularfire2/database-deprecated'; import {Item} ...

"Unlock the power of NGXS by leveraging the raw state values

I'm having trouble locating an example in the NGXS documentation that demonstrates how to properly type the state object. Specifically, I am looking for guidance on typing the return value of the snapshot method of Store. For instance: this.store.sn ...

Is it possible for me to develop a service that seamlessly integrates with my controller or perhaps a component?

Correct me if I'm mistaken, but my understanding is that I can directly access and display the data from my service. In other words, by injecting my service, I can easily read from and write to it in multiple components. However, in order for the serv ...