我可以将mat-form-field外包为自定义组件或指令吗?

时间:2019-05-20 14:54:16

标签: angular-material angular-reactive-forms

我有此表单字段:

    <mat-form-field>
        <input matInput type="password" placeholder="password" formControlName="password" autocomplete="new-password">

        <mat-hint align="end">Must have one letter, and one number</mat-hint>
        <mat-error *ngIf="password.invalid && password.touched" class="has-text-danger">
            That password sucks...
        </mat-error>

    </mat-form-field>

我想将其用作自定义组件,例如:

<password-form-field formControlName="password"></password-form-field>

在父组件中提供formControlName。这样可能吗?

这样做的原因是我想在许多其他组件中使用它。.

1 个答案:

答案 0 :(得分:1)

您应该在password-form-field组件中实现ControlValueAccessor,以便能够将password-form-fieldformControlName一起使用。这是一个例子;

https://medium.com/@majdasab/implementing-control-value-accessor-in-angular-1b89f2f84ebf

.....

或者,您可以使用formControl指令代替formControlName来达到相同的结果,如下所示:

首先,您应将@Input添加到password-form-field

@Component({
    selector: "password-form-field",
    templateUrl: "./password-form-field.component.html",
    styleUrls: ["./password-form-field.component.scss"]
})
export class PasswordFormFieldComponent {
    @Input() formCtrl: FormControl;

    constructor() {}
}

然后按如下所示在您的password-form-field.component.html中使用它:

<mat-form-field>
  <input matInput type="password" placeholder="password" [formControl]="formCtrl" autocomplete="new-password" />
  <mat-hint align="end">Must have one letter, and one number</mat-hint>
  <mat-error *ngIf="password.invalid && password.touched" class="has-text-danger">
    That password sucks...
  </mat-error>
</mat-form-field>

最后,您可以在以下任何地方使用它;

/** if password is defined as a standalone FormControl */
<password-form-field [formCtrl]="password"></password-form-field> 

OR

/** if password is defined in a FormGroup named myFormGroup  */
<password-form-field [formCtrl]="myFormGroup.get('password')"></password-form-field>