mov*_*ila 49 typescript angular2-ngmodel angular
我做了一个简单的UI,它包含两个组件(父和子).
UI的作用是当我在Child组件的输入框中键入一些内容时.该值将使用ngModel更改.
子组件以这种方式工作正常.
// Child Component
@Component({
selector: 'child',
template: `
<p>{{sharedVar}}</p>
<input [(ngModel)]="sharedVar">
`
})
export class ChildComponent {
sharedVar: string;
}
Run Code Online (Sandbox Code Playgroud)
现在我有一个父组件,我打算使用与Child Component相同的值.
我将Child Component添加到Parent模板中,并使用依赖注入来调用Child Component sharedVar.
// Parent Component
@Component({
selector: 'parent',
template: `
<h1>{{sharedVar}}</h1>
<child></child>
`,
directives: [ChildComponent],
providers: [ChildCompnent]
})
export class ParentComponent {
sharedVar: string;
constructor(child: ChildComponent) {
this.sharedVar = child.sharedVar;
}
}
Run Code Online (Sandbox Code Playgroud)
问题是当我在输入框中输入时,值<p>会自动更改,而父组件中的值<h1>不会更改.
Mar*_*cok 101
我们可以使用[(x)]父模板中的语法来实现与子进程的双向数据绑定.如果我们使用名称创建一个Output属性xChange,Angular将自动更新父属性.emit()每当孩子改变值时,我们确实需要一个事件:
import {Component, EventEmitter, Input, Output} from 'angular2/core'
@Component({
selector: 'child',
template: `
<p>Child sharedVar: {{sharedVar}}</p>
<input [ngModel]="sharedVar" (ngModelChange)="change($event)">
`
})
export class ChildComponent {
@Input() sharedVar: string;
@Output() sharedVarChange = new EventEmitter();
change(newValue) {
console.log('newvalue', newValue)
this.sharedVar = newValue;
this.sharedVarChange.emit(newValue);
}
}
@Component({
selector: 'parent',
template: `
<div>Parent sharedVarParent: {{sharedVarParent}}</div>
<child [(sharedVar)]="sharedVarParent"></child>
`,
directives: [ChildComponent]
})
export class ParentComponent {
sharedVarParent ='hello';
constructor() { console.clear(); }
}
Run Code Online (Sandbox Code Playgroud)
我sharedVarParent在ParentComponent中使用的只是为了证明父和子中的名称不必相同.
您可以设置outputs从子级到父级的事件发射器通信 ( )。例如这样:
@Component({
selector: 'child',
template: `
<p>Child: {{sharedVar}}</p>
<input [(ngModel)]="sharedVar" (ngModelChange)="change()">
`
})
export class ChildComponent {
@Output() onChange = new EventEmitter();
sharedVar: string;
change() {
this.onChange.emit({value: this.sharedVar});
}
}
Run Code Online (Sandbox Code Playgroud)
和父组件中:
@Component({
selector: 'parent',
template: `
<h1>{{sharedVar}}</h1>
<child (onChange)="sharedVar = $event.value"></child>
`,
directives: [ChildComponent]
})
export class ParentComponent {
sharedVar: string;
constructor() {
}
}
Run Code Online (Sandbox Code Playgroud)
演示: http://plnkr.co/edit/T2KH4nGKPSy6GEvbF1Nb? p=info
| 归档时间: |
|
| 查看次数: |
34060 次 |
| 最近记录: |