라이브러리 추가
1 |
npm install --save jquery @types/jquery |
메뉴 생성
jquery 컴포넌트 생성
1 |
ng g component jquery |
라우팅 패스를 추가한다.
1 |
{path: 'jquery', component: JqueryComponent}, |
메뉴 링크 추가
1 2 3 |
<li class="nav-item" routerLinkActive="active"> <a class="nav-link" href routerLink="/jquery">jquery</a> </li> |
jquery 메뉴를 클릭해서 jquery works가 드는지 확인하자.
화면 구성
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<table class="table table-striped"> <thead> <tr> <th>완료</th> <th>todo</th> <th>생성일</th> <th>수정일</th> <th>삭제</th> </tr> </thead> <tbody id="todo_list"> </tbody> </table> |
tbody 노드를 쉽게 찾기 위해서 todo_list 라는 id를 추가했다.
모델 데이터 얻기
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
import { Component, OnInit } from '@angular/core'; import {HeroService} from '../hero.service'; import * as $ from 'jquery'; @Component({ selector: 'app-jquery', templateUrl: './jquery.component.html', styleUrls: ['./jquery.component.scss'] }) export class JqueryComponent implements OnInit { todoList; constructor(private heroService: HeroService) { } ngOnInit() { this.getTodoList(); } getTodoList() { $.ajax({ url: 'http://www.javabrain.kr:8080/api/todo', method: 'GET', dataType: 'json', success: (data) => { console.log(data); this.todoList = data; // this.refresh(); } }); } } |
여기서 dataType은 무엇을 의미하는가? 보내는 데이터가 아니라 받을때 json으로 받겠다는 의미이다.
ajax로 데이터를 비동기로 가져온다. 가져온 데이터를 콘솔로 찍어서 확인해보자.
뷰 생성하기
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
refresh() { console.log('refresh'); $('#todo_list').empty(); this.todoList.forEach(function(item, index) { let todo = '<tr>' + '<td>' + (item.isFinished ? '완료' : '미완료') + '</td>' + (item.isFinished ? '<td style="text-decoration: line-through">' : '<td>') + item.todo + '</td>' + '<td>' + item.created + '</td>' + '<td>' + item.updated + '</td>' + '<td>' + '<button type="button">삭제</button>' + '</td>' + '</tr>'; $('#todo_list').append(todo); }); } |
먼저 todo_list 의 자식노드를 모두 삭제하고(empty) 모델 데이터로 노드를 만들어서 todo_list 노드의 자식 노드로 루프를 돌면서 각각 삽입한다.