如何使用AngularJS 2创建可重用的嵌套子窗体组件 [英] How to create reusable nested subform component using AngularJS 2
问题描述
我正在使用Angular2创建一个Web应用程序.我有几个数据输入屏幕,用户必须在其中输入邮政地址,这是诸如Company或Person之类的实体的较大数据输入的一部分.
I am using Angular2 to create a web application. I have several data entry screens where the user must input a postal address which is part of a larger data entry for entities like Company or Person.
因此,我自然希望创建一个地址表单组件,该组件可以作为子表单重用,并且可以以某种方式嵌入或包含在较大的表单中.这似乎应该可行,但我无法创建示例或查找示例.我试图创建一个具有FormBuilder作为输入的子组件,但这不起作用.
So naturally I would like to create an Address Form Component that could be reused as a subform and somehow embedded or included within larger forms. This seems like it should be possible but I haven't been able to create an example or find and example. I've tried to create a subcomponent that has a FormBuilder as an input, but this doesn't work.
对我来说,问题是我似乎无法成功传达封闭的<形式>标记到我的html模板.
the problem for me is that I can't seem to successfully communicate the enclosing < form > tag to my html template.
有人知道这种方法吗?
推荐答案
仅适用于< =角度< = 2.0.0 RC
我不知道这是否是一个好方法,但似乎可行
I don't know if this is a good approach but it seems to work
@Component({
selector: 'address-form',
providers: [],
styles: [':host {display: inline-block; border: 1px solid blue;}'],
template: `
<input [ngFormControl]="street">
<input [ngFormControl]="zip">
`,
directives: []
})
export class AddressForm {
street = new Control('', Validators.minLength(3));
zip = new Control('', Validators.required);
isSet:boolean;
@Input() group;
constructor() {}
ngOnChanges() {
setTimeout(()=> {
this.group.control.addControl('street', this.street);
this.group.control.addControl('zip', this.zip);
});
}
}
<form #f="ngForm">
<input ngControl="custId">
<address-form ngControlGroup="address" #addrGroup="ngForm" [group]="addrGroup"></address-form>
</form>
另请参见Kara与Plunker的评论 https://github.com/angular/angular/issues/10251#issuecomment-238737954
See also this comment from Kara with Plunker https://github.com/angular/angular/issues/10251#issuecomment-238737954
这篇关于如何使用AngularJS 2创建可重用的嵌套子窗体组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!