Sign in
Log inSign up

(Solved) How to bind ngModel value across components?

Pablo Ivan G. Soto's photo
Pablo Ivan G. Soto
·Jul 23, 2016

Say you have about.component.ts: (Edit: the following represents my solution)

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

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

export class AboutComponent {
  @Input() model: any;
}

And notes.component.ts:

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

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

export class NotesComponent {
  @Input() model: any;
}

Both files are components from 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 [model]="model"></about-section>
    <notes-section [model]="model"></notes-section>
  `,
  directives: [AboutComponent, NotesComponent]
})

export class AppComponent {
  private model: any = {}
}

My question is, how would you bind the ngModel name property from about.component.ts to notes.component.ts and viceversa so whenever you write your name, the change is reflected both in the notes component and the about component? (Solved: I extracted the model outside of each component scope and made it an object, then I made the API publicly available in the main component so the tho children have access using the Input decorator).