1

In my script I change value of an element with jquery(same with javascript), but model connected with this element was not changed. here is this element:

<input type="text" class="form-control" id="username" placeholder="Username" [(ngModel)]="user.username">

When I change value manually then model gets updated aswell. What should it be?

Thanks

Maxim
  • 243
  • 3
  • 18

1 Answers1

-1

Se plunker

Here an example:

Parent Component:

import { Comp1Component } from './../comp1/comp1.component';
import { Component, OnInit } from '@angular/core';

 @Component({
   selector: 'app-comp-parent',
   template:`
      <p>ngModel: {{sharedVarParent}}</p>
       <app-comp1 [comp1]="sharedVarParent" (sharedVarChange)="onChange($event)"></app-comp1>
       <hr />
       <app-comp2 [comp2]="sharedVarParent" (sharedVarChange)="onChange($event)"></app-comp2>
    `
 })
 export class CompParentComponent implements OnInit {
   sharedVarParent ='Initial';
   onChange(ev){
      this.sharedVarParent = ev;
   }
}

COmp1:

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

@Component({
   selector: 'app-comp1',
   template:`
      <input type="text" id="username" placeholder="{{comp1}}" [ngModel]="comp1" (ngModelChange)="change($event)">
      <div>{{comp1}}</div>`
})
export class Comp1Component implements OnInit {
  @Input() comp1;
  @Output() sharedVarChange = new EventEmitter();
  change(newValue) {
    this.comp1 = newValue;
    this.sharedVarChange.emit(newValue);
  }
}

Comp2

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

@Component({
  selector: 'app-comp2',   
  template:`
    <input type="text" id="username" placeholder="{{comp2}}" [ngModel]="comp2" (ngModelChange)="change($event)">
    <div>{{comp2}}</div>
  `   
})
export class Comp2Component implements OnInit {
  @Input() comp2;
  @Output() sharedVarChange = new EventEmitter();
  change(newValue) {  
     this.comp2 = newValue;
     this.sharedVarChange.emit(newValue);
  }
}

enter image description here

sTx
  • 1,213
  • 13
  • 32
  • Do the components have to be nested in DOM? I don't know how @Input() and @Output() work – Maxim Apr 13 '17 at 06:04
  • COmp1 and COmp2 are siblings and COmp-parent is the parent of both and also the link between them. Comp-parent(as a component template) is inside in app.component.html – sTx Apr 13 '17 at 06:49