2017-08-14 46 views
1

角版本:V4.2.x的后续Angular2-form:是否可以包含孩子对父母NgForm valuechanges的输入?

我有包含子组件的一种形式:

parent.component.ts

@Component({ 
    template: ` 
     <form #myForm="ngForm"> 
      <child-component [parentForm]="myForm" [inputName]="'myName'"></child-component> 
     </form> 
    ` 
}) 
export class ParentComponent implements OnInit { 
    @ViewChild("myForm") myForm: NgForm; 
} 

child.component.ts

@Component({ 
    template: ` 
     <input [name]="inputName" [(ngModel)]="petName"></input> 
    ` 
}) 
export class ChildComponent implements OnInit { 
    @Input("parentForm") parentForm: NgForm; 
    @Input("inputName") inputName: string; 
    petName: string; 

    ngOnInit() { 
     this.parentForm.valueChanges.subscribe(changes => { 
      console.log(JSON.stringify(changes)); 
     }); 
    } 
} 

当在子输入f现在,我看不到控制台中的任何更改。但是,如果我将相同的代码从子代移动到父代并删除子组件,则在键入时会在控制台中输出更改。

有什么想法?谢谢!

+0

您的子组件实现'ControlValueAccessor'。 – 12seconds

回答

2

你可以尝试添加ngModel指令父NgForm手动:

child.component.html

<input [name]="inputName" #model="ngModel" [(ngModel)]="petName"> 

child.component.ts

export class ChildComponent implements OnInit { 
    ... 
    @ViewChild("model") ngModel: NgModel; 

    ngOnInit() { 
    this.parentForm.addControl(this.ngModel); // <== add this 
    this.parentForm.valueChanges.subscribe(changes => { 
     console.log(JSON.stringify(changes)); 
    }); 
    } 
} 

Plunker Example