簡體   English   中英

Angular 8:組件內部的formControlName下面有多個嵌套級別

[英]Angular 8: formControlName inside component multiple nested levels below

使用此資源,我想在多個嵌套級別上實現 formControlName。

Angular 2 - 組件內的 formControlName

假設實際的 formGroup 位於子 formControlName 組件上方 3 個組件級別,

如果父組件就在子組件旁邊,則 ControlValueAccessor 起作用。 然而,高於(祖父)形式的多個級別不起作用。

是否有替代服務或多個輸入/輸出? 或者這些是唯一的方法?

A--> Component with formGroup 
   B---> Component container
      C---> Component container
        D ---> Component with FormControlName (should pass to Component A)

組件 A 會從類似這樣的不同子組件中收集多個表單控件名稱,

輸入文本.ts

export class InputTextComponent implements  AfterViewInit, ControlValueAccessor  {
  @Input() disabled: boolean;
  @Output() saveValue = new EventEmitter();

  value: string;
  onChange: () => void;
  onTouched: () => void;

  writeValue(value: any) {
    this.value = value ? value : "";
  }

  registerOnChange(fn: any) {this.onChange = fn}

  registerOnTouched(fn: any) {this.onTouched = fn}

  setDisabledState(isDisabled) {this.disabled = isDisabled}
}

輸入文本.html

 <input .. />

您可以考慮四個選項:

1) 使用 FormControlName 在您的組件上提供 ControlContainer

d.component.ts

@Component({
  ...
  viewProviders: [
    {
      provide: ControlContainer,
      useExisting: FormGroupDirective
    }
  ]
})
export class DComponent implements OnInit {

Ng 運行示例

2)創建提供 ControlContainer 的簡單指令

@Directive({
  selector: '[provideContainer]',
  providers: [
    {
      provide: ControlContainer,
      useExisting: FormGroupDirective
    }
  ]
})
export class ProvideContainerDirective {
}

然后將此指令放置在節點層次結構頂部的某個位置

d.component.html

<ng-container provideContainer>
  <input formControlName="someName">
</ng-container>

Ng 運行示例

3) 使用 FormControlDirective 而不是 FormControlName 指令

FormControlDirective需要傳遞FormControl實例

<input [formControl]="control">

您可以通過 DI 獲取此實例:

d.component.ts

export class DComponent implements OnInit {
  control;
  constructor(private parentFormGroupDir: FormGroupDirective) { }

  ngOnInit() {
    this.control = this.parentFormGroupDir.control.get('someName');
  }

Ng 運行示例

或使用一些綁定您的組件的服務。

d.component.ts

export class DComponent implements OnInit {
  control: FormControl;

  constructor(private formService: FormService) { }

  ngOnInit() {
    this.control = this.formService.get('someName');
  }

Ng 運行示例

4)將 FormGroup 作為 Input 道具傳遞給孩子或通過 DI 或服務獲取它,然后使用 formGroup 指令包裝您的 input[formControlName]

d.component.html

<ng-container [formGroup]="formGroup">
 <input formControlName="..."
</ng-container>

Ng 運行示例

堆棧閃電戰

我想這就是你要找的

遵循 stackblitz 示例

我創建了 3 個組件comp3 comp1 comp2

我在appModule formGroupcomp1 => comp2 => comp3

comp3中,我創建了age屬性的formControl並將其綁定。 在從comp3更改age的值時,它將反映在父組件中,即appComponent

希望這可以幫助!

干杯!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM