我应该如何创建一个包含mat-form-field和输入的组件?

时间:2019-02-01 11:39:32

标签: angular angular-material2 angular-reactive-forms

我正在一个使用大量嵌套反应式表单的项目中,我想创建一个将Mat-Form-Field和输入都包装到一个组件中的控件,但是当我以表单的形式尝试它时,不断出错。

我认为问题在于控件位于数组中,因为它单独运行时似乎可以正常工作。

当前使用下面的代码,我收到以下错误消息BasicInputComponent.html:2错误错误:找不到名称为“ firstName”的控件

我也尝试过使用ControlValueAccessor,但是我不确定这是否是正确的处理方式,当我尝试使用它时,我无法从“从原地到远方”来识别它是否正确。 t有效。

我意识到该示例是非常基本的,但是我确实需要该控件在表单数组中可用,以便可以在系统的其他位置使用它。

子组件html:

<mat-form-field floatLabel="never" class="ng-untouched ng-pristine ng-invalid">
    <input matInput #input [placeholder]="placeholder" [type]="type" [attr.maxlength]="maxlength" type="text" [formControlName]="controlName"/>
    <mat-hint *ngIf="maxlength" align="end">{{input.value?.length || 0}}/{{maxlength}}</mat-hint>
</mat-form-field>

子组件ts

@Component({
    selector: 'app-basic-input',
    templateUrl: './basic-input.component.html',
    styleUrls: ['./basic-input.component.css'],
    viewProviders: [{ provide: ControlContainer, useExisting: FormGroupDirective }]
})
export class BasicInputComponent { 

    @Input() placeholder: string;
    @Input() controlName: string;
    @Input() maxlength: number | null;

    constructor() {}
}

父html:

<form [formGroup]="vehicle">
    <div formArrayName="occupants" *ngFor="let occupant of vehicle.get('occupants')['controls']; let i = index;">
        <div [formGroupName]="i">
              <app-basic-input placeholder="First Name" controlName="firstName" maxlength="25"></app-basic-input>
        </div>
    </div>
</form>

父母ts:

    vehicle= this.fb.group({
        occupants: this.fb.array([
            this.fb.group({
                firstName: ['', Validators.required],
                lastName: ['', Validators.required]
            })
        ])
    })  

1 个答案:

答案 0 :(得分:0)

尝试在 parent.html 中拆分此行:

...
<div formArrayName="occupants" *ngFor="let occupant of vehicle.get('occupants')['controls']; let i = index;">
...
</div>
...

进入

...
<div formArrayName="occupants">
  <div *ngFor="let occupant of vehicle.get('occupants')['controls']; let i = index;">
  ...
  </div>
</div>
...
相关问题