角度8:组件下方的多个嵌套级别内的formControlName

使用此资源,我想在多个嵌套级别上实现formControlName。

Angular 2 - formControlName inside component

假设实际的formGroup位于子formControlName组件之上的3个组件级别,

如果父级组件位于子级旁边,则

ControlValueaccessor可以工作。但是,以上(祖父)形式的多个级别不起作用。

是否有Service的替代品,还是有多个输入/输出?还是这些是唯一的方法?

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

组件A将从与此相似的不同子组件收集多个表单控件名称,

InputText.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}
}

InputText.html

 <input .. />
louislee511 回答:角度8:组件下方的多个嵌套级别内的formControlName

您可以考虑四个选项:

1)在组件上为ControlContainer提供FormControlName

d.component.ts

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

Ng-run Example

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-run Example

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-run Example

或使用与您的组件相关的某些服务。

d.component.ts

export class DComponent implements OnInit {
  control: FormControl;

  constructor(private formService: FormService) { }

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

Ng-run Example

4)将FormGroup作为Input道具传递给孩子,或者通过DI或服务获取它,然后使用formGroup指令包装您的输入[formControlName]

d.component.html

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

Ng-run Example

,

Stackblitz

我认为这就是您要寻找的

按照stackblitz示例

我已经创建了3个组件comp1 comp2 comp3

我已经在appModule中创建了注册表单,并将formGroup传递给comp1 => comp2 => comp3

comp3中,我创建了formControl属性的age并将其绑定。 从age更改comp3的值时,它将反映在父组件中,即appComponent

希望这会有所帮助!

干杯!

本文链接:https://www.f2er.com/3161113.html

大家都在问