使用javascript或jquery更改元素值后更改angular2组件模型

时间:2017-04-12 12:48:45

标签: javascript jquery angular

在我的脚本中,我使用jquery更改元素的值(与javascript相同),但未更改与此元素关联的模型。这是这个元素:

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

当我手动更改值时,模型也会更新。它应该是什么?

由于

1 个答案:

答案 0 :(得分:-1)

Se plunker

这是一个例子:

父组件:

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