【问题标题】:Angular 10 two way Data Binding in Reactive form using ngif for form validation使用 ngif 进行表单验证的反应式表单中的 Angular 10 双向数据绑定
【发布时间】:2020-11-11 07:48:12
【问题描述】:

我正在以反应形式使用两种方式的数据绑定,但我认为它无法正常工作,因为在 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;
    }
  }

请帮我解决问题

【问题讨论】:

    标签: angular-ng-if angular10 two-way-binding


    【解决方案1】:

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

    尝试改用这个:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-04
      • 2020-01-13
      • 1970-01-01
      • 2020-12-05
      相关资源
      最近更新 更多