如何在自定义控件中添加所需的星号?

How to add required asterisk in a custom control?

我正在使用 angular 6 创建一个包含自定义表单控件的自定义组件。到目前为止,我已经在我的组件中实现了 ControlValueAccessor

我的自定义控件是来自 Angular Material 的简单 MatSelect 组件。我想在需要该控件时显示星号 (*)。

到目前为止,我已经让自定义控件正常工作,但是向组件添加 required 属性并没有向我的控件添加星号!

<app-provinces formControlName="projectProvince" required></app-provinces>

我应该为它定义一个 @Input 变量并手动处理它,还是应该自动完成?

是的,您应该在组件中添加 required @Input()

像这样:

<div class="form-group m-form__group row" [ngClass]="{
                    'has-danger': formGroup.controls[formControlName].invalid && formGroup.controls[formControlName].touched,
                    'has-success': formGroup.controls[formControlName].valid && formGroup.controls[formControlName].touched,
                    'has-no-action': formGroup.controls[formControlName].untouched
                                }">
        <label class="col-form-label col-lg-3 col-sm-12" [for]="formControlId">
            {{formControlLabel}}
            <span *ngIf="isRequired" class="required" aria-required="true"> * </span>
        </label>
        <div class="col-lg-4 col-md-9 col-sm-12">
            <select placeholder="place_holder_text" [disabled]="disabled" [class]="formControlName" [id]="formControlId" [data]="formControlItems"  (click)="setAsTouched()" (valueChanged)="store($event)"></select>
            <div class="form-control-feedback">{{formControlErrorText || 'Required Field May Not Be Empty'}}</div>
            <span class="m-form__help">{{formControlHelpText}}</span>
        </div>
    </div>

组件:

@Input('required') isRequired: boolean;

用法示例:

<select-form-control
    [required]="true"
    [group]="myFormGroup"
    label="Name"
    name="name"
    controlId="name"
    [inputItems]="array"
    helpText="Enter..."
    [value]="name"
    (valueChange)="someMethod($event)">
</select-form-control>