max*_*der 5 javascript angular2-forms angular angular4-forms
根据角度的最新版本,@ angular/forms导出以下内容:
export {FormControlDirective} from './directives/reactive_directives/form_control_directive';
export {FormControlName} from './directives/reactive_directives/form_control_name';
export {FormGroupDirective} from './directives/reactive_directives/form_group_directive';
export {FormArrayName} from './directives/reactive_directives/form_group_name';
export {FormGroupName} from './directives/reactive_directives/form_group_name';
Run Code Online (Sandbox Code Playgroud)
FormContolName并且FormControlDirective,FormGroupName和FormGroupDirective,但FormArrayName没有FormArrayDirective,为什么?
我认为这是没有必要的。好吧,你可以创建指令,比如
@Directive({
selector: '[formArrayName]'
})
export class FormArrayDirective implements OnInit {
formArray: FormArray;
constructor(
private el: ElementRef,
@Host() @Optional() public form: FormGroupDirective
) {}
ngOnInit() {
this.formArray = this.form
? (this.form.form.get(
this.el.nativeElement.getAttribute('formArrayName')
) as FormArray)
: null;
}
}
Run Code Online (Sandbox Code Playgroud)
更新之前在表单中我们有 FormGroupDirective,我认为最好有 FormGroup
新指令
@Directive({
selector: '[formArrayName]'
})
export class FormArrayDirective implements OnInit {
formArray: FormArray;
form:FormGroup;
constructor(
private el: ElementRef,
@Host() @Optional() private formDirective: FormGroupDirective
) {}
ngOnInit() {
this.formArray = this.formDirective
? (this.formDirective.form.get(
this.el.nativeElement.getAttribute('formArrayName')
) as FormArray)
: null;
this.form=this.formDirective?this.formDirective.form:null
}
}
Run Code Online (Sandbox Code Playgroud)
该指令公开两个属性:form和,但要小心,您只能从具有ngAfterViewInitformArray的组件访问此属性@ViewChild(FormArrayDirective)
好奇心,想得到它的目的是什么?