如何验证角号“#”中的模板驱动形式

时间:2020-10-26 06:48:06

标签: angular angular10 angular-template-form

大家好?如果有值,我该如何验证#permissionInput,顺便说一下,这是有角度的。

  <input
                          #permissionInput
                          type="text"
                          class="col dropdown"
                          placeholder="Select permission group ..."
                          (focus)="onFocus(dropdownContent)"
                          (blur)="onBlur()"
                          (input)="onInput(permissionInput.value)"
                          [ngClass]="{ 'is-invalid': pGroup.invalid && (pGroup.dirty || pGroup.touched) }"
                        />
 <small
                      *ngIf="permissionInput.value.invalid && (permissionInput.value.dirty || permissionInput.value.touched)"
                      class="form-text text-muted danger invalid-feedback1 ml-1"
                    >
                      <div *ngIf="permissionInput.value.errors.required">
                        Name is required.
                      </div>
                    </small>

``

1 个答案:

答案 0 :(得分:1)

您可以按照以下方式进行操作:

<input
    #permissionInput="ngModel"
    type="text"
    required
    class="col dropdown"
    placeholder="Select permission group ..."
    (focus)="onFocus(dropdownContent)"
    (blur)="onBlur()"
    [ngModel]="somevariable"
    (ngModelChange)="onInput(permissionInput.value)"
    [ngClass]="{ 'is-invalid': pGroup.invalid && (pGroup.dirty || pGroup.touched) }"
/>
<small
    *ngIf="permissionInput.errors && (permissionInput.value.dirty || permissionInput.value.touched)"
    class="form-text text-muted danger invalid-feedback1 ml-1"
>
    <div *ngIf="permissionInput.errors.required">
        Name is required.
    </div>
</small>
somevariable: string;

onInput(value: string) {
   ...
   this.somevariable = value;
}

要使输入在没有值时引发错误,您需要在输入中添加required。 另外,您可以使用errors而不是permissionInput.errors来访问permissionInput.value.errors