首页 > 解决方案 > 具有自定义验证的 Angular 组件

问题描述

我有一个 Angular 5 组件,它基本上只是一个标签和输入

<div class="form-group">
    <label for="wwid">WWID</label>
    <input id="wwid" required ...lots of attrs...>
</div>

然后我使用 CSS 定义了一个样式:

.ng-invalid:not(form) {
  border-left: 5px solid #a94442; /* red */
}

当该字段为空白时,我得到两个红色边框。我想要的输入字段上的一个,也是我不想要的标签右侧的一个。如何去除标签上的红线?

在此处输入图像描述

这是组件使用的实际完整 HTML。

<ng-template #listSelectionFormatter let-r="result">
    <span>{{r.wwid}} - {{r.fullName}}</span>
</ng-template>

<div class="form-group">
    <label *ngIf="labelText" for="wwid">
        {{ labelText }}
        <span *ngIf="isRequired">&nbsp;<sup class="requiredIndicator">*</sup></span>
    </label>

    <!-- inputFormatter is the format for what is placed into the input field after choosing from the dropdown -->
    <input id="wwid" type="text"
           class="form-control"
           placeholder="Search by WWID, IDSID, Name or Email"
           (selectItem)="onWorkerSelected($event.item)"
           (input)="onTextFieldChanged($event.target.value)"
           [ngModel]="selectedWorker"
           [ngbTypeahead]="search"
           [inputFormatter]="selectedResultsFormatter"
           [resultTemplate]="listSelectionFormatter"
           [disabled]="disabled"
           [required]="required"
    />
    <span *ngIf="searching">searching&hellip;</span>
    <div class="invalid-feedback" *ngIf="searchFailed">Lookup failed.</div>
</div>

如果需要的requiredIndicator话,这只是我用来显示星号的旧样式,并使用了这个 CSS:

.requiredIndicator {
  color: red;
  font-size: larger;
  vertical-align: baseline;
  position: relative;
  top: -0.1em;
}

标签: cssangularvalidationng-bootstrap

解决方案


推荐阅读