2016-07-29 70 views
1

我有2個組件:RegistrationComponent和RegistryComponent。Angular 2親子溝通

RegistrationComponent:

@Component({ 
selector: 'registration_page', 
template: 
'<div> 
    <registry_form [model]="parentModel"></registry_form> 
    <label>{{parentModel}}</label> 
</div>, 
styleUrls: [...], 
directives: [...], 
providers: [] 
}) 
export class RegistrationComponent 
{ 
    parentModel : string; 

    constructor() 
    { 
     this.parentModel = "parent" 
    } 
} 

RegistryComponent:

@Component({ 
selector: 'registry_form', 
template: 
' 
    <label for="name">name {{model}}</label> 
    <input [(ngModel)]="model" required > 
', 
styleUrls: [...], 
directives: [...] 
}) 

export class RegistryFormComponent 
{ 
    @Input() model; 
} 

當我寫在輸入一些文字在RegistryComponent我可以看到的變化,但不是在RegistrationComponent巫父組件。我錯過了什麼?

+0

https://toddmotto.com/component-events-event-emitter-output-angular-2 – Matt

回答

3

看這個代碼:

<registry_form [model]="parentModel"></registry_form> 

[]部分是指,這將是一個「輸入」結合型。你可以讓事情工作2種方式:

1)更改綁定是

<registry_form [(model)]="parentModel"></registry_form> 
       ^ ^

例如「盒子裏的香蕉」。但是,這僅僅是一個「語法糖」,所以你也需要實現一個Output() modelChange屬性:

@Component({ 
    selector: 'registry_form', 
    template: ` 
    <label for="name">name {{model}}</label> 
    <input [(ngModel)]="model" (ngModelChange)="modelChange.next($event)" required > 
    `, 
}) 
export class RegistryFormComponent { 
    @Input() model: any; 
    @Output() modelChange = new EventEmitter(); 
} 

2)使parentModelname屬性的對象,並通過這整個對象:

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

@Component({ 
    selector: 'registry_form', 
    template: ` 
    <label for="name">name {{model.name}}</label> 
    <input [(ngModel)]="model.name" required > 
    `, 
}) 
export class RegistryFormComponent { 
    @Input() model: any; 
} 

@Component({ 
    selector: 'registration_page', 
    template: ` 
    <div> 
     <registry_form [model]="parentModel"></registry_form> 
     <label>{{parentModel.name}}</label> 
    </div>`, 
    directives: [RegistryFormComponent], 
}) 
export class RegistrationComponent { 
    parentModel : any; 

    constructor() { 
     this.parentModel ={name:"parent"}; 
    } 
} 
+0

謝謝你的男人!你救了我......我管理這個工作以消除所有註冊表組件,並將他的HTML註冊到註冊頁面......但這是我尋找的解決方案! –

+0

哪個選項最好? @Dethariel –

0

因爲它是單向綁定。孩子有自己的範圍。每當你在孩子身上做的改變都會留在孩子身上。

如果孩子需要更新並通知家長,需要使用事件。