看看我的傻瓜: http://plnkr.co/edit/hB34VjxP98uz1iAYS7Dw?p=preview
名称包含在myform.form中,但组件内部的Name1不包含在内。如何在myform中包含Name1?
<div class="container">
<div [hidden]="submitted">
<h1>Hero Form</h1>
<form #heroForm="ngForm">
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" required
[(ngModel)]="modelname"
name="name" #name="ngModel" >
<div [hidden]="name.valid || name.pristine" class="alert alert-danger">
Name is required
</div>
<inner></inner>
</div>
</form>
{{heroForm.form.value | json}}
</div>
inner.component模板:
<label for="name">Name1</label>
<input type="text" class="form-control" required
[(ngModel)]="modelname1"
name="name1" #name1="ngModel" >
<div [hidden]="name1.valid || name1.pristine" class="alert alert-danger">
Name1 is required
</div>
答案 0 :(得分:1)
我已修复您的代码以实现您的最终目标。现在名称和名称1都包含在表单中,并且值将显示在您的
上我已经从你的plnkr创建了一个fork并修复了你的代码以支持你的用例。请看一下:http://plnkr.co/edit/UHkwJ9?p=preview
inner.component.html更改为:
<label for="name">Name1</label>
<input type="text" class="form-control" required
[(ngModel)]="modelname1" [formModel]="form" [registerModel]="name2"
name="name2" #name2="ngModel" >
<div [hidden]="name2.valid || name2.pristine" class="alert alert-danger">
Name1 is required
</div>
hero-form.component.ts更改为:
<inner [form]="heroForm"></inner>
添加了New Directive,它将在现有表单引用中注册一个新控件:
import { Directive, ElementRef, Input, OnInit } from '@angular/core';
import { NgModel, NgForm } from '@angular/forms';
@Directive({
selector: '[formModel]'
})
export class FormModelDirective implements OnInit {
private el: HTMLInputElement;
@Input('formModel') public form: NgForm;
@Input('registerModel') public model: NgModel;
constructor(el: ElementRef) {
this.el = el.nativeElement;
}
ngOnInit() {
if (this.form && this.model) {
this.form.form.addControl(this.model.name, this.model.control);
}
}
}
输出图片:
参考:plnkr.co/edit/GG2TVHHHGbAzoOP5mIRr?p=preview