gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 08:55:03 24 4
gpt4 key购买 nike

我有这个表单字段:

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

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

最佳答案

您应该实现ControlValueAccessor在您的 password-form-field 组件中,以便能够将 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>

或者

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

关于angular-material - 我可以将 mat-form-field 外包为自定义组件或指令吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56223466/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com