Reactive Form Angular 和传递控制

问题描述 投票:0回答:2
angular angular-reactive-forms
2个回答
1
投票

因为你使用的是

FormGroup
在我看来最干净的方法是使用
FormControlName

<app-text-input [label]="'test'" [formControlName]="'test'" [inputId]="'test'"></app-text-input>

您的

form
将具有控件名称的位置

this.form = this.fb.group({
  test: ['', Validators.required]
});

fb
是 formBuilder 以防你不熟悉它


0
投票

我使用这样的反应形式

someForm.ts

<form
  novalidate
  autocomplete='off'
  [formGroup]='this.parentForm'
>
  <app-input-text
    [parentForm]='this.someForm'
    [formCtrlName]="'search'" // => of course, it could be dynamic
  >
  </app-input-text>
</form>

应用程序输入文本.ts

export class InputTextComponent implements OnInit {

  @Input() parentForm: FormGroup;
  @Input() formCtrlName: string;
  @Input() placeholder: string;

  constructor() { }

  ngOnInit() {
  }

}

app-input-text.html

<form
  novalidate
  autocomplete='off'
  [formGroup]='this.parentForm'
>
  <input
    matInput
    [placeholder]='this.placeholder'
    [formControlName]='this.formCtrlName'
  >
</form>

我喜欢将组件拆分得更细... 我用这种方式可以在父表单中操作所有验证... 输入可以非常可重用,我在很多项目中都使用这种方式并取得了很好的效果。

© www.soinside.com 2019 - 2024. All rights reserved.