Angular2-form:是否可以将子输入包含到父 NgForm 值更改中?
Angular2-form: Is it possible to include child input to parent NgForm valuechanges?
Angular版本:v4.2.x
我有一个包含子组件的表单:
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));
});
}
}
在子输入字段中键入时,我在控制台中看不到任何变化。但是,如果我将相同的代码从子组件移动到父组件并删除子组件,则更改会在键入时在控制台中输出。
有什么想法吗?谢谢!
您可以尝试手动将 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));
});
}
}
Angular版本:v4.2.x
我有一个包含子组件的表单:
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));
});
}
}
在子输入字段中键入时,我在控制台中看不到任何变化。但是,如果我将相同的代码从子组件移动到父组件并删除子组件,则更改会在键入时在控制台中输出。
有什么想法吗?谢谢!
您可以尝试手动将 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));
});
}
}