2017-04-12 53 views
1

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

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

当我手动更改值,然后模型更新以及。它应该是什么?

由于

+0

能否请您阐述更没有得到明确的想法 –

+0

请让我知道究竟需要说明 – Maxim

+0

你到底让我们知道,你想实现什么,你的要求不明确 –

回答

-1

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); 
    } 
} 

组合物2

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

+0

组件是否必须嵌套在DOM中?我不知道@Input()和@Output()如何工作 – Maxim

+0

COmp1和COmp2是同胞,而COmp-parent是两者的父亲,也是它们之间的链接。 Comp-parent(作为组件模板)位于app.component.html中 – sTx