기본 콘텐츠로 건너뛰기

[Angular Tutorial 02] The Hero Editor

[Angular Tutorial 02] The Hero Editor

[Angular Tutorial 02] The Hero Editor

https://angular.io/tutorial/toh-pt1

다음 명령어를 통하여 generate 타입의 heroes 라는 이름의 component 를 생성 합니다.

ng generate component heroes

herose component가 생성 되었습니다.

컴포넌트 하위에는 css, html, ts, spec.ts 파일이 포함되어 있습니다.

app/heroes/heroes.component.ts (initial version) 파일의 구조를 살펴 봅시다.

import { Component , OnInit } from '@angular/core' ;

@ Component ({ selector: 'app-heroes' , templateUrl: './heroes.component.html' , styleUrls: [ './heroes.component.css' ] }) export class HeroesComponent implements OnInit {

constructor () { }

ngOnInit () { }

}

반드시 모든 Components 에는 Angular core library를 import 해야 합니다.

Component Class 는 반드시 Annotation 표시를 해 주어야 합니다 ex) @Component.

You always import the Component symbol from the Angular core library and annotate the component class with @Component.

@Component is a decorator function that specifies the Angular metadata for the component.

1. selector— the component's CSS element selector

3. templateUrl— the location of the component's template file.

4. styleUrls— the location of the component's private CSS styles.

heroes.component.ts (hero property) 파일에서 property 를 추가 해 보겠습니다.

export class HeroesComponent implements OnInit {

hero = 'Windstorm' ; constructor () { }

ngOnInit () { } }

그리고 heroes.component.html 파일을 다음과 같이 수정 합니다.

< p > {{hero}}

이제 src/app/app.component.html 에 view 를 추가하여 결과 화면에 출력 시켜 봅시다.

필요 없는 내용은 삭제 하였습니다.

< div style = " text-align:center" > < h1 > {{ title }} < app-heroes >

여기까지의 화면입니다.

이제 Hero 라는 Class 를 생성 해 보겠습니다.

src/app 하위에 hero.ts 라는 파일을 생성하여 다음과같이 작성 합니다.

export class Hero { id : number ; name : string ; }

src/app/heroes/heroes.component.ts 파일로 가서 hero Class 를 import 해줍니다.

그리고 HeroesComponent Class 를 다음과같이 수정합니다.

import { Component , OnInit } from '@angular/core' ; import { Hero } from '../hero' ;

@ Component ({ selector: 'app-heroes' , templateUrl: './heroes.component.html' , styleUrls: [ './heroes.component.css' ] }) export class HeroesComponent implements OnInit {

hero : Hero = { id: 1 , name: 'Windstorm' };

constructor () { }

ngOnInit () { }

}

hero 의 타입이 변경되었으니 component.html 의 출력 형식도 변경 해 주어야 겠지요?

heroes.component.html (HeroesComponent's template) 파일을 다음과 같이 수정 합니다.

※ 참고 ※

UppeCasePipe

텍스트를 모두 대문자로 변환 합니다.

사용 방법 : {{ value_expression | uppercase }}

< h2 > {{hero.name | uppercase}} Details < div >< span > id: {{hero.id}} < div >< span > name: {{hero.name}}

{{hero.name | uppercase}}의 내용 WINDSTORM 은 대문자로 출력됩니다.

그리고 양방향 데이터 바인딩을 위하여 다음과같이 component.html 파일을 다시 수정합니다.

src/app/heroes/heroes.component.html (HeroesComponent's template)

< div > < label > name: < input [(ngModel)] = "hero.name" placeholder = "name" >

[(ngModel)] is Angular's two-way data binding syntax. (양방향 데이터 바인딩 문법입니다.)

하지만 ngModel 을 사용하기 위햇는 FormsModule 을 import 해주어야 합니다.

app.module.ts 파일을 열어 다음과같이 import 해줍니다.

app.module.ts (FormsModule symbol import)

상단에 import 를 해 준 다음에는 NgModule 의 import 부분에 이름을 꼭 넣어주어야 합니다.

그리고 app.module.ts 파일을 살펴보면 CLI를 통해서 생성한 heroes.component 가 자동으로 선언 되어있는것을 볼 수있습니다.

물론 declarations 에도 선언되어 있습니다. CLI 를 사용할 때 편리한 장점 중 하나입니다.

import { BrowserModule } from '@angular/platform-browser' ; import { NgModule } from '@angular/core' ; import { FormsModule } from '@angular/forms' ; // <-- NgModel lives here import { AppComponent } from './app.component' ; import { HeroesComponent } from './heroes/heroes.component' ;

@ NgModule ({ declarations: [ AppComponent , HeroesComponent ], imports: [ BrowserModule , FormsModule // FomsModule 추가 ], providers: [], bootstrap: [ AppComponent ] }) export class AppModule { }

여기까지의 모습입니다.

You used the CLI to create a second HeroesComponent.

You displayed the HeroesComponent by adding it to the AppComponent shell.

You applied the UppercasePipe to format the name.

You used two-way data binding with the ngModel directive.

You learned about the AppModule.

You imported the FormsModule in the AppModule so that Angular would recognize and apply the ngModel directive.

You learned the importance of declaring components in the AppModule and appreciated that the CLI declared it for you.

CLI 를 이용하여 새로운 HeroesComponent 를 생성 하였습니다. HeroesComponent 를 AppComponent 에 추가하여 출력 하였습니다. UppercasePipe 를 이용하여 문자열을 대문자로 바꾸어 출력 해보았습니다. 양방향 데이터 바인딩 ngModel 을 선언 하였습니다.

from http://nina-life.tistory.com/37 by ccl(A) rewrite - 2020-03-06 14:20:41

댓글

이 블로그의 인기 게시물

[Angular] Router 라우터 정리

[Angular] Router 라우터 정리 Angular2 버전 이후를 기준으로 정리한 글입니다. 라우터는 URL을 사용하여 특정 영역에 어떤 뷰를 보여 줄지 결정하는 기능을 제공한다. 전통적인 서버사이드 렌더링을 하는 웹 사이트는 주소가 바뀔 때마다 서버에 전체 페이지를 요청하고 전체 페이지를 화면에 렌더링한다. 매 요청시 전체 페이지를 새로 랜더링하는 것은 비효율적이기 때문에 라우터를 이용하여 필요한 부분만 랜더링을 한다면 효율적일 것이다. 라우터는 URL에 해당하는 컴포넌트를 화면에 노출하고 네비게이션을 할 수 있는 기능을 가지고 있다. Router 구성 요소 Router – 라우터를 구현하는 객체이다. Navigate() 함수와 navigateByUrl() 함수를 사용하여 경로를 이동할 수 있다. RouterOulet – 라우터가 컴포넌트를 태그에 렌더링하는 영역을 구현하는 Directive이다. Routes – 특정 URL에 연결되는 컴포넌트를 지정하는 배열이다. RouterLink – HTML의 앵커 태그는 브라우저의 URL 주소를 변경하는 것이다. 앵귤러에서 RouterLink를 사용하면 라우터를 통해 렌더링할 컴포넌트를 변경할 수 있다. ActivatedRoute – 현재 동작하는 라우터 인스턴스 객체이다. Router 설정 라우터를 사용하기 위해서는 먼저 Router 모듈을 import 해야 한다. import { RouterModule, Routes } from '@angular/router'; 라우터에서 컴포넌트는 고유의 URL과 매칭된다. URL과 컴포넌트는 아래와 같이 Routes 객체를 설정하여 지정할 수 있다. 아래의 예에서는 디폴트 path에서는 MainComponent가 노출이 되고 product-list path에서는 ProductListComponent가 노출이 되도록 설정을 한 것을 볼 수 있다. const routes: Routes = [ { pa...

[Angular] Controller

[Angular] Controller Step02_controller.html // angular 모듈 만들기 var myApp = angular.module( "myApp" ,[]); // Ctrl1 이라는 이름의 컨트롤러 만들기 myApp.controller( "Ctrl1" ,[ "$scope" , function ($scope){ $scope. name = "김구라" ; $scope.clicked = function (){ alert ( "버튼을 눌렀네?" ); }; $scope.nums = [ 10 , 20 , 30 , 40 , 50 ]; }]); // Ctrl2 이라는 이름의 컨트롤러 만들기 myApp.controller( "Ctrl2" ,[ "$scope" , function ($scope){ $scope. name = "원숭이" ; $scope.friends = [ {num: 1 , name : "김구라" ,addr: "노량진" }, {num: 2 , name : "해골" ,addr: "행신동" }, {num: 3 , name : "원숭이" ,addr: "동물원" } ]; }]); 내이름은 : {{name}} 눌러보셈 {{tmp}} 너의 이름은 : {{name}} 번호 이름 주소 {{tmp.num}} from http://heekim0719.tistory.com/164 by ccl(A) rewrite - 2020-03-07 09:21:16

JQuery - $ 사용 유형.

JQuery - $ 사용 유형. 최근에 새로운 Javascript 프레임워크와 라이브러리들이 많이 등장했고 시장 점유율 또한 많이 변동 되었다고 한다. 특히 요새 대새는 Angular와 React라고들 한다. 그리고 Jquery 요즘 누가써? Jquery 퇴물이야 등등... 그런 이야기들을 종종 찾아볼 수 있는데, 유행은 돌고 돌듯이 결국 Jquery가 몰락할 일은 없다고 생각하는 바, 묵묵히 Jquery를 고집하기로 한다...ㅎㅎ 먼저 Jquery 교과서랄까.. 기본 문법을 배울 수 있는 링크를 걸어둔다. https://www.w3schools.com/jquery 여기서 기초들을 다 익힐 수 있다. 프로그래밍 문법을 한번이라도 봤다면 + - * / 같은 연산 while, for 등은 다 비슷하기 때문에 $ 사용법만 잘 알면 될 것 같다. $ syntax 사용유형 일단 기본적으로 $는 JQuery에서 미리 정해놓은 변수 값이다. : JQueryStatic 1. $( ) : JQueryObject 가장 많이 사용하는 형태이다. 괄호 안에 들어 갈 수 있는 것들은 클래스 이름, 아이디, 셀렉터 등이다. 예를 들어 $('p')이면 현재 html 페이지에 있는 모든 를 JqueryObject로 가져오겠다는 것이다. hide()는 제이쿼리 메서드이다. $('p')는 제이쿼리 오브젝트이기 때문에 제이쿼리 메서드를 사용할 수 있다. 그중의 하나인 hide()를 사용해 보았다. 결과이다. 에는 스타일이 적용이 되었다. 해당 태그에는 jquery의 메서드가 적용이 된 것을 확인할 수 있다. 2. $.함수 : 플러그인 개발 또는 기본 전역함수 플러그인을 개발 할 때나 Jquery가 갖고 있는 기본 전역함수들을 사용할 때 쓴다. 전역함수에는 여러개가 있는데 그중에 개인적으로 많이 쓰는 것은 $.ajax({}), $.each({}) 등이 있다. 이 함수들의 사용방법은 따...