컴포넌트는 화면 구현을 담당하는 template과 비즈니스 로직을 담당하는 컴포넌트 클래스 간의 상호작용을 위한 방법으로 바인딩을 이용한다.
app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
// 변수 선언
title = '바인딩실습';
name = '홍길동';
age = 20;
address = '서울';
}
app.component.ts에서 선언된 변수를 html파일에서 사용한다.
<h1>{{ title }}</h1>
이름: {{ name }}<br />
<!-- 클래스 속성 바인딩 -->
나이: {{ age }}<br />
주소: {{ address }}<br />
import { Component } from '@angular/core';
@Component({
selector: 'app-root', // 이 컴포넌트를 쓰기위한 명칭 app-root -> index.html 에서 사용
templateUrl: './app.component.html', // 화면 구성
styleUrls: ['./app.component.css'], // 스타일 지정
})
export class AppComponent {
title = '바인딩 실습';
uesr = {
// 객체
name: '홍길동',
age: 20,
address: '서울',
};
}
{{ title }}<br />
<!-- 객체로 접근할 수 있다 . -->
이름은 {{ user.name }}이고 나이는 {{ user.age }} 입니다. 사는 곳은
{{ user.address }}
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-book',
templateUrl: './book.component.html',
styleUrls: ['./book.component.css'],
})
export class BookComponent {
titleName = '도서목록';
books = [
{
id: 'p01',
name: '위험한 식탁',
price: 2000,
date: '20190401',
img: 'a.jpg',
},
{
id: 'p02',
name: '공부의 비결',
price: 2000,
date: '20190401',
img: 'b.jpg',
},
{
id: 'p03',
name: '오메르타',
price: 2000,
date: '20190401',
img: 'c.jpg',
},
{
id: 'p04',
name: '행복한 여행',
price: 2000,
date: '20190401',
img: 'd.jpg',
},
{
id: 'p05',
name: '해커스 토익',
price: 2000,
date: '20190401',
img: 'e.jpg',
},
{
id: 'p06',
name: '도로안내서',
price: 2000,
date: '20190401',
img: 'f.jpg',
},
];
getTitleName() {
return this.titleName;
}
ngOnInit(): void {}
}
// 메서드 접근 getTitleName()
<h1>{{ getTitleName() }} {{ books.length }}권</h1>
<ul>
<li *ngFor="let book of books"> <!-- for 문 books중 하나하나를 book으로 객체를 뽑아 접근 -->
<img src="../../assets/image/{{ book.img }}" width="100" height="100" />
{{ book.name }}
</li>
</ul>