Angular 10 使用 ngif 进行表单验证的 Reactive 表单中的双向数据绑定

Angular 10 two way Data Binding in Reactive form using ngif for form validation

我正在以反应形式使用两种方式的数据绑定,但我认为它不能正常工作,因为在 ngif 条件下,只有当条件有效而不是其他条件时。 In this image I want that if admin enter anything else than 'teacher' in Designation input then subject will be disable otherwise it should be enable for 'teacher'

这是代码

<td><div class="form-group mb-2">
        <label for="email" class=" mx-sm-3">Designation</label>
        <input type="text" formControlName="Designation"  class="form-control"  [ngClass]="{ 'is-invalid': submitted && f.Designation.errors }" #Designation/>
                    <div *ngIf="submitted && f.Designation.errors" class="invalid-feedback">
                      <div *ngIf="f.Designation.errors.required">Designation is required</div>
    </div>
      </div>
    </td>

ngif 条件

<ng-template
  *ngIf="techer();then ifShow; else ifNotShow">
</ng-template>

<ng-template #ifShow>

  <div class="form-group mb-2">
    <label for="sel1" class="mx-sm-3"> Subjects: </label>
    <select class="form-control" formControlName="Subjects" id="sel1"  [ngClass]="{ 'is-invalid': submitted && f.Subjects.errors }" >
      <option *ngFor="let account of subjects" [value]="account.Sub_Title">{{ account.Sub_Title }}</option>
    </select>
      <div *ngIf="submitted && f.Subjects.errors" class="invalid-feedback">
      <div *ngIf="f.Subjects.errors.required">Subject is required</div>
  </div>
  </div>
</ng-template>

<ng-template #ifNotShow>

  <div class="form-group mb-2">
    <label for="sel1" class="mx-sm-3"> Subjects: </label>
    <select class="form-control" formControlName="Subjects" id="sel1"  [ngClass]="{ 'is-invalid': submitted && f.Subjects.errors }" [attr.disabled]="true">
      <option *ngFor="let account of subjects" [value]="account.Sub_Title">{{ account.Sub_Title }}</option>
    </select>
      <div *ngIf="submitted && f.Subjects.errors" class="invalid-feedback">
      <div *ngIf="f.Subjects.errors.required">Subject is required</div>
  </div>
  </div>

</ng-template>

在 component.ts 文件中

techer(){

    if(this.form.get('Designation').value === 'Teacher || teacher'){
      return !this.Tr; //Tr is boolean value which initially false
    }
    else{
      return this.Tr;
    }
  }

请帮我解决问题

您的 if/else 语句不正确,您不能使用 OR ||像这样的字符串中的运算符。您的 if else 语句现在总是会在第一次检查时失败。

尝试改用它:

if (this.form.get('Designation').value.toLowerCase() === 'teacher') {

}