我可以将MAT-FIEL场外壳外包为自定义组件或指令吗?



我有此表单字段:

    <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-1b89f2f2f84ebf

.....

另外,您可以通过使用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> 

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

最新更新