我有此表单字段:
<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。这样可能吗?
这样做的原因是我想在许多其他组件中使用它。.
答案 0 :(得分:1)
您应该在password-form-field
组件中实现ControlValueAccessor,以便能够将password-form-field
与formControlName
一起使用。这是一个例子;
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>