網站搜尋

javascript - Angular 為列表顯示多個按鈕


我有一個儲存格清單。我想要在另一個畫面上顯示它們的位置參考。我想要以按鈕的形式顯示這個屬性。我希望每個儲存格都有一個按鈕,並且在按鈕上寫上儲存格的位置參考。現在儲存格太多了,所以我不想一個一個地新增。我嘗試過使用 ng-repeat,但沒能成功,還出現了很多錯誤。我應該怎麼做才能達到我想要的效果?

HTML:

<div fxLayout="column" class="mat-elevation-z2 responsive-grid">
  <table>
    <tr ng-repeat="LocationReference in cell">
      <td>
        <button>{{ cell.LocationReference }}</button>
      </td>
    </tr>
  </table>
</div>

TS :

cell: ICell;

儲存格介面:

export interface ICell {
  CellId?: number;
  CellName?: string;
  LocationReference?: string;
}

答案#1

ng-repeat 是用於 angularJS,在標籤中你說你正在使用 angular。Angular 與 angularJS 不同,在 angular 中你可以使用 ngFor

如果你有一個儲存格列表,你需要對你的儲存格進行迴圈,而不是對單個儲存格的屬性進行迴圈。而且將按鈕放在單個儲存格中完全沒有意義,所以我移除了表格結構。只有在你顯示表格數據時才使用表格。

如果你正在顯示表格數據,請將表格結構加回去,但現在你應該能看到這應該如何運作:cells 是存放所有單元格的陣列,應該是 ICell[] 類型

<div fxLayout="column" class="mat-elevation-z2 responsive-grid">
  <button *ngFor=let cell of cells>{{cell.LocationReference}}</button>
</div>

答案#2

你應該使用 *ngFor 而不是 ng-repeat。ng-repeat 用於 AngularJS,而 *ngFor 用於 Angular。如果你要遍歷一個陣列,你可以這樣做:

<div fxLayout="column" class="mat-elevation-z2 responsive-grid">
  <div *ngFor="let item of cell">
    <button>{{ item.LocationReference }}</button>
  </div>
</div>

如果你要遍歷一個字典,你可以這樣做:

<div fxLayout="column" class="mat-elevation-z2 responsive-grid">
  <div *ngFor="let key of cell | keyvalue">
    <button>{{ item.value}}</button>
  </div>
</div>