跨组件绑定ngModel值

时间:2016-07-23 04:08:16

标签: angularjs angular

假设你有 about.component.ts ,其中包含以下内容:

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

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

export class AboutComponent {

}

然后你有 notes.component.ts

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

@Component({
  selector: 'notes-section',
  template: `
    <p>{{name || 'user'}}</p>
  ` 
})

export class NotesComponent {

}

这两个文件都是 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></about-section>
  <notes-section></notes-section>
  `,
  directives: [AboutComponent, NotesComponent]
})

export class AppComponent { }

我的问题是,如何将 about.component.ts 的ngModel'name'属性绑定到 notes.component.ts ,这样每当你写下你的名字时,更改会反映在notes组件和about组件中吗?

1 个答案:

答案 0 :(得分:3)

一种方法是使用EventEmitter

@Component({
  selector: 'about-section',
  template: `
    <input [ngModel]="name" (ngModelChange)="name = $event; modelChanged.emit($event)">
    <p>{{name || 'user'}}</p>
  ` 
})
export class AboutComponent {
  @Output() modelChanged = new EventEmitter();
}

@Component({
  selector: 'notes-section',
  template: `<p>{{name || 'user'}}</p>` 
})
export class NotesComponent {}

@Component({
  selector: 'my-app',
  template: `
   <about-section (modelChanged)="notes.name = $event"></about-section>
   <notes-section #notes></notes-section>`,
  directives: [AboutComponent, NotesComponent]
})
export class AppComponent { }

检查demo plunker here

首先,我在框[(ngModel)]="name"https://angular.io/docs/ts/latest/guide/template-syntax.html#!#two-way-binding-with-ngmodel)中提取香蕉,从包含EventEmitter的组件中发出ngModel个事件。

<input [ngModel]="name" (ngModelChange)="name = $event; modelChanged.emit($event)">

然后我只是在父组件中订阅了这个事件:

<about-section (modelChanged)="notes.name = $event"></about-section>

但在此之前我继续引用其他组件以便能够更改name,如上面的代码notes.name = $event所示,其中$event表示引发事件的“有效负载”(输入在这种情况下的价值)。

<notes-section #notes></notes-section>