Angular7 ControlValueAccesor作为FormArray

时间:2019-04-28 22:49:19

标签: angular angular7

我需要开发一个可重用的列表组件,该组件将返回对象列表,简单对象列表,这些对象应分配给formGroup对象值中的键。

有没有办法在列表的Angular中进行自定义控件?

这是我尝试过的事情,也是我打算做的事情,希望代码能自我解释。

 const filteredData = allData.filter(({ existingLabel }) => {
    for (let i = 0; i < tabData.length(); i++) {
        existingLabel === tabData[i].label;
    }
});

然后是孩子(列表组件定义为此)

// PARENT COMPONENT 
<div [formGroup]="form" [ngSubmit]="submit()">
    <custom-list formControlName="profiles"></custom-list>
    <custom-list formControlName="groups"></custom-list>
    <custom-list formControlName="users"></custom-list>

    <button>Submit</button>
</div>

@Component(...)
export class ParentComponent implements OnInit {
    form: FormGroup;

    constructor(private _formBuilder: FormBuilder) {
        // Method One
        this.form = this._formBuilder.group({
          profiles: ['', Validators.required],
          groups: ['', Validators.required],
          users: ['', Validators.required]
        });

        // Method Two. Don't know how is should be or if it will work?
        this.form = this._formBuilder.group({
          profiles: this._formBuilder.array([]),
          groups: this._formBuilder.array([]),
          users: this._formBuilder.array([])
        });
    }
}

表单值应如下所示

// CHILD COMPONENT
@Component({
  selector: 'custom-list',
  providers: [{
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => CustomListComponent),
      multi: true
  }]
})
export class CustomListComponent implements OnInit, ControlValueAccessor { 
    form: FormGroup;

    constructor(private _formBuilder: FormBuilder) {
        this.form = this._formBuilder.group({
          elements: this._formBuilder.array([], Validators.required)
        });
    }

    writeValue(val: any): void {
        val && this.form.setControl('elements', this._formBuilder.array(val));
    }
}

以这种方式工作,但列表在表单组键中添加了一个额外的键,这是我添加到子表单中的组。

{
    profiles: [{id: 1, name: "profile 1"}, {id: 2, name: "profile 2"}],
    groups: [{id: 1, name: "group 1"}, {id: 2, name: "group 2"}],
    users: [{id: 1, name: "user 1"}, {id: 2, name: "user 2"}]
}

1 个答案:

答案 0 :(得分:0)

扩展了我的评论,stackblitz 你的孩子

    <div *ngFor="let group of myFormArray.controls;let i=index" [formGroup]="group">
        <input formControlName="prop1">
    <div *ngIf="group.get('prop1').invalid">Prop1 Required</div>
    <input formControlName="prop2"/>
    <div *ngIf="group.get('prop2').invalid">Prop2 Required</div>
  @Input()myFormArray:FormArray

您的父母

<div [formGroup]="form" [ngSubmit]="submit()">
    <custom-list [myFormArray]="form.get('profiles')"></custom-list>
    <custom-list [myFormArray]="form.get('groups')></custom-list>
    <custom-list [myFormArray]="form.get('users')></custom-list>

    <button>Submit</button>
</div>