You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular中如何合并*ngIf与readonly属性实现单个Input组件复用

你之前的尝试存在语法错误,*ngIf仅用于控制元素是否渲染,不能将readonly属性的配置逻辑写入*ngIf的表达式中。你的场景不需要通过*ngIf切换元素,仅需动态绑定对应属性即可实现需求,合并后的代码如下:

<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]="editIndex === i ? 'legacy' : 'none'">
      <input matInput placeholder="{{clients.name}}" [(ngModel)]="clients.name" [readonly]="editIndex !== i">
    </mat-form-field>
  </mat-cell>
</ng-container>

以上代码的逻辑说明:

  • mat-form-field的appearance属性通过三元表达式动态赋值,匹配你原有两个组件的样式规则:编辑态(editIndex === i)时使用legacy样式,非编辑态时使用none样式
  • input的readonly属性直接绑定布尔判断结果:非编辑态时自动为true,输入框只读;编辑态时自动为false,输入框可编辑

内容的提问来源于stack exchange,提问作者sirtz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.16 12:15:04