为什么在@angular表单中没有FormArrayDirective?

9
根据最新版本的Angular文档,@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';

为什么有FormControlNameFormControlDirectiveFormGroupNameFormGroupDirective,但是FormArrayName没有对应的FormArrayDirective呢?这是IT技术相关内容。

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中访问。
好奇,获取它的目的是什么?

刚刚看到这个问题,虽然我不知道提问者的目的是什么,但我的目的只是为了理解为什么会有差异。如果FormArrayDirective是不必要的,那么为什么FormGroupDirective是必要的呢? - AbdealiJK

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接