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

Can I outsource a mat-form-field as a custom component or directive?

我有这个表单域:

    <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。这样的事情可能吗?

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

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

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

.....

或者,您可以使用 formControl 指令而不是 formControlName 来实现相同的结果,如下所示:

首先你应该添加一个 @Inputpassword-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> 

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