我有一个表,它使用数组keyData中的数据,我想按下一个按钮,向该数据添加一行.

从console.logs中,我可以看出keyData数组插入了额外的行,但这并没有反映在UI中.

以下是该网页的内容:

<mat-tab label="Keys">
  <button mat-fab extended (click)="onAddKey()">
    <mat-icon>add</mat-icon>
    Add Key
  </button>

  <table mat-table [dataSource]="keyData" #keyTable class="mat-elevation-z8 demo-table">
    <ng-container matColumnDef="active">
      <th mat-header-cell *matHeaderCellDef> Active </th>
      <td mat-cell *matCellDef="let element"> {{element.active}} </td>
    </ng-container>

    <ng-container matColumnDef="key-id">
      <th mat-header-cell *matHeaderCellDef> Key ID </th>
      <td mat-cell *matCellDef="let element"> {{element.key_id}} </td>
    </ng-container>

    <ng-container matColumnDef="description">
      <th mat-header-cell *matHeaderCellDef> Description </th>
      <td mat-cell *matCellDef="let element"> {{element.description}} </td>
    </ng-container>

    <ng-container matColumnDef="checkbox">
      <th mat-header-cell *matHeaderCellDef>
        <input type="checkbox">
      </th>
      <td mat-cell *matCellDef="let element"> </td>
    </ng-container>

    <tr mat-header-row *matHeaderRowDef="keyColumns"></tr>
    <tr mat-row *matRowDef="let row; columns: keyColumns;"></tr>
  </table>
</mat-tab>

以下是组件:

@Component({
  selector: 'app-policies',
  standalone: true,
  imports: [CommonModule, MatCheckboxModule, MatIconModule, MatCardModule, MatTabsModule, FormsModule, MatFormFieldModule, MatInputModule, MatSidenavModule, MatTableModule],
  templateUrl: './policies.component.html',
  styleUrl: './policies.component.scss',
  changeDetection: ChangeDetectionStrategy.Default
})
export class PoliciesComponent {
  @ViewChild(MatTable) keyTable!: MatTable<any>;

  keyColmuns: string[] = ["active", "key-id", "description"]
  keyData: any = []

  constructor(
    private endpointService: EndpointService,
  ) { }

  onAddKey() {
    const newKeyId = Math.random().toString(36).slice(-10)

    this.endpointService.makeRequest({
      params: {
        key_id: newKeyId,
        policy_id: this.openedRow.policy_id,
      },
      method: "aaaaaaaaaaaa"
    },
      "aaaaaaaaaa"
    ).subscribe({
      next: (value: any) => {
        console.log('value', value)
        this.keyData.push({
          active: 1,
          api_set_key: value.result.api_set_key,
          description: "",
          key_id: newKeyId,
        })
        // A new row is being inserted here but this is not displayed in the UI until I refresh the page.
        this.keyTable.renderRows();
        console.log('this.keyData', this.keyData)
      },
      error: err => {
        console.error('Error:', err)
      },
    })

  }

我也试过从ChangeDetectorRef分跑到detectChanges();分,但也没有奏效.

推荐答案

您是否可以try 进行下面的更改,这将创建对数组的新引用,这可能会导致重新加载网格.

...
).subscribe({
      next: (value: any) => {
        console.log('value', value)
        this.keyData.push({
          active: 1,
          api_set_key: value.result.api_set_key,
          description: "",
          key_id: newKeyId,
        })
        this.keyData = [...this.keyData]; // <-- changed here!
        // A new row is being inserted here but this is not displayed in the UI until I refresh the page.
        this.keyTable.renderRows();
        console.log('this.keyData', this.keyData)
      },
      error: err => {
        console.error('Error:', err)
      },
    })
...

Angular相关问答推荐

如何在Angular 17中使用Angular—calendum?

身份验证卫士给了我17个Angular 的任何类型

第15角Cookie的单元测试用例

Angular:将服务注入非独立组件导致应用程序中断

NG-BOOTSTRAPP SCROLLESPY没有高度就不能工作?

倒计时计时器,每10秒重新启动一次,共4次

react 形式之间的循环关系

MonoTypeOperatorFunction不可分配给OperatorFunction类型的参数

Angular CLI 与 Angular 版本不兼容

当信号的值发生变化时,模板不会更新

如何以Angular 改变环境

在ionic 5中获取url传递的参数

Angular 2 中的 ChangeDetectionStrategy.OnPush 和 Observable.subscribe

使用directive指令将类添加到host元素中

如何在 Angular 5 HttpInterceptor 中添加多个标头

使用 rxjs 处理刷新令牌

Angular 7 测试:NullInjectorError:No provider for ActivatedRoute

ERROR 错误:StaticInjectorError(AppModule)[UserformService -> HttpClient]:

检测指令中输入值何时更改

得到了预期表达式的插值 ({{}})