将 Angular 中的 * ngIf 属性 组合成一个输入

Combine * ngIf property in Angular into an Input

我在 Angular 11 和 Angular material 中有一个项目,我试图将 *ngIf 属性 与 readOnly 属性 结合起来以避免放置两个输入。

这是我的 component.html:

<ng-container matColumnDef="name">
        <mat-header-cell *matHeaderCellDef>Name</mat-header-cell>
        <mat-cell *matCellDef="let clients; let i = index">
          <mat-form-field *ngIf="editIndex!=i" floatLabel="never" [appearance]="'none'">
              <input matInput placeholder="{{clients.name}}" [(ngModel)]="clients.name" [readonly]="true">
          </mat-form-field>
          <mat-form-field *ngIf="editIndex==i" floatLabel="never" [appearance]="'legacy'">
              <input matInput placeholder="{{clients.name}}" [(ngModel)]="clients.name">
          </mat-form-field>
        </mat-cell>
      </ng-container>

现在我有两个 mat-form-field 每个都有一个输入,一个 [readonly]="true" 取决于 *ngIf = "editIndex! = I" 属性。我怎样才能将两者结合起来,只用一个输入输入一个 mat-form-field?

这是我想尝试的,但我不知道该怎么做或是否可以做到:

<ng-container matColumnDef="name">
    <mat-header-cell *matHeaderCellDef>Name</mat-header-cell>
    <mat-cell *matCellDef="let clients; let i = index">
      <mat-form-field floatLabel="never" [appearance]="'none'">
          <input matInput placeholder="{{clients.name}}" [(ngModel)]="clients.name" *ngIf="editIndex!=i; [readonly]="true"">
      </mat-form-field>
    </mat-cell>
</ng-container>

怎么样...?

<input matInput ... [readonly]="editIndex!=i">

您还可以设置条件 readonlyappearance

 <mat-form-field floatLabel="never" [appearance]="editIndex != i ? 'none' : 'legacy'">
     <input matInput placeholder="{{clients.name}}" 
     [(ngModel)]="clients.name" [readonly]="editIndex!=i"">
 </mat-form-field>

你可以这样做:

<ng-container matColumnDef="name">
   <mat-header-cell *matHeaderCellDef>
     Name
   </mat-header-cell>
   <mat-cell *matCellDef="let clients; let i = index">
        <mat-form-field 
           *ngIf="editIndex!=i" 
           floatLabel="never" 
           [appearance]="'none'" // Since you are not binding with any variable here, you can replace with appearance="none"
        >
           <input 
              matInput 
              placeholder="{{clients.name}}" // You can replace this with [placeholder]="clients.name"
              [(ngModel)]="clients.name" 
              [readonly]="editIndex !== i"
            />
        </mat-form-field>
   </mat-cell>
</ng-container>