ค้นหาเว็บไซต์

angularjs - การใช้งานเงื่อนไข if else ภายใน mat-cell ของ mat-table - Angular 5


ฉันพยายามที่จะใช้เงื่อนไข if else ภายใน mat-cell ของ mat-table ในแอป Angular ของฉัน แต่ฉันได้รับข้อผิดพลาดจากคอนโซล "ERROR Error: StaticInjectorError(AppModule)[NgIf -> TemplateRef]: "

รหัสของฉันคือ

<ng-container matColumnDef="role">
    <mat-header-cell *matHeaderCellDef>Role</mat-header-cell>        
    <mat-cell *matCellDef="let user" ngIf="{{user.roles.length == 1}}">
        Admin          
    </mat-cell>
  </ng-container>

ความช่วยเหลือใด ๆ ก็ชื่นชมอย่างมาก

คำตอบ #1

คุณมี ngIf แต่ควรมีเครื่องหมายดอกจันนำหน้า: *ngIf

นอกจากนี้ ด้วยแอตทริบิวต์ directive ที่ผูกค่าเช่น *ngIf คุณไม่จำเป็นต้องใช้วงเล็บปีกกาอยู่ข้างใน แค่ทำ *ngIf="user.roles.length == 1" ก็เพียงพอแล้ว

อย่างไรก็ตาม โดยปกติแล้วคุณไม่สามารถมีคำสั่งสองคำสั่งในองค์ประกอบเดียวกันที่มีเครื่องหมายดาว (*), ดังนั้นการใช้ <ng-container> อีกตัวอาจเป็นวิธีแก้ไขที่ถูกต้อง:

<ng-container matColumnDef="role">
  <mat-header-cell *matHeaderCellDef>Role</mat-header-cell>
  <ng-container *ngIf="user.roles.length == 1">
    <mat-cell *matCellDef="let user" >
      Admin          
    </mat-cell>
  </ng-container>
</ng-container>

คำตอบ #2

การเพิ่มตัวห่อ ng-container ใช้ได้ผลในการดึงวัตถุ user บนคอนเทนเนอร์หลักและใช้ตัวแปรที่เข้าถึงจากคอนเทนเนอร์หลักนั้นในคอนเทนเนอร์ลูกสำหรับ *ngIf

    <ng-container matColumnDef="role">
      <th *matHeaderCellDef mat-header-cell>Role</th>
      <td *matCellDef="let user" mat-cell>
        <ng-container *ngIf="user.roles.length == 1;else conditionNotMet">
          Admin (Condition is met)
        </ng-container>
      </td>

      <ng-template #conditionNotMet>
        What ever logic...
      </ng-template>
    </ng-container>

บทความที่เกี่ยวข้อง