9

根据最新版本的角度,@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';

FormContolNameand FormControlDirective, FormGroupNameand FormGroupDirective, 但是FormArrayName没有FormArrayDirective, 为什么?

4

1 回答 1

1

我认为这是不必要的。好吧,你可以创建指令,有些像

@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;
  }
}

在表单之前更新我们有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
  }
}

该指令公开了两个属性:formformArray,但请注意,您只能从具有@ViewChild(FormArrayDirective)ngAfterViewInit的组件访问此属性

好奇心,得到它的目的是什么?

于 2021-06-25T07:04:15.700 回答