[230105 - TIL] angular material table로 목록만들기

Dongwoo Kim·2023년 1월 5일
0

TIL / WIL

목록 보기
70/113

1. 프로젝트 셋업

아래에서 작성한 프로젝트 이어서 작업


2. 프로젝트 구조

AppModule
    ├── (AppService)
	│	
    ├── HomeModule
	│
	└── UserModule
        │
    	└── UserInfoComponent (UserTable)
  • UserInfoComponent에서 유저 목록을 볼 수 있는 테이블을 만들어보자
  • angular material을 계속 사용하기 위해서 Dokerfile에
    RUN ng add @angular/material 추가
# ../Dockerfile

FROM node:14.21-alpine

RUN mkdir /angular
WORKDIR /angular

RUN npm update & npm install -g @angular/cli@13

COPY package.json package-lock.json ./

COPY . .

RUN ng add @angular/material

3. User Data 생성

# data-class/user.ts

export class User {
  id: number;
  username: string;
  created_at: string;

  constructor() {
    this.id = 0;
    this.username = '';
    this.created_at = '';
  }
}

export const USER_DATAS: Array<User> = [
  { id: 1, username: 'username 1', created_at: '2023-01-01' },
  { id: 2, username: 'username 2', created_at: '2023-01-02' },
  { id: 3, username: 'username 3', created_at: '2023-01-03' },
  { id: 4, username: 'username 4', created_at: '2023-01-04' },
  { id: 5, username: 'username 5', created_at: '2023-01-05' },
  { id: 6, username: 'username 6', created_at: '2023-01-06' },
];

4. MatTableModule 임포트하기

# user/user.module.ts

...
import { MatTableModule } from '@angular/material/table';

@NgModule({
  declarations: [
    UserComponent, 
    UserInfoComponent, 
    UserInfoDetailComponent
  ],
  imports: [
	...
    MatTableModule
  ],
})
export class UserModule {}

5. table 정의

# user/user-info/user-info.component.ts

...
import { UserInfoDetailComponent } from './user-info-detail/user-info-detail.component';
import { USER_DATAS } from 'src/app/data-class/user';

@Component({
  selector: 'app-user-info',
  templateUrl: './user-info.component.html',
  styleUrls: ['./user-info.component.css'],
})
export class UserInfoComponent implements OnInit {
  constructor() {}
  ngOnInit(): void {}

  displayedColumns: string[] = ['id', 'username', 'created_at'];
  dataSource = USER_DATAS;
}
# user/user-info/user-info.component.html

<table mat-table [dataSource]="dataSource" class="mat-elevation-z8">

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

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

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

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

6. 적용 화면



구현 코드

https://github.com/kimphysicsman/TIL-230105

참고

profile
kimphysicsman

0개의 댓글