Angular 覚え書きです。
$ node --version
v18.20.4
$ npm --version
10.7.0
諸事情により Angular v15 を使います。
ng コマンドをグローバルに入れたくないので次の手順で Angular v15 のプロジェクトのベースをつくります。
tmp ディレクトリを作成して、ng コマンドをいれます。
$ mkdir tmp
$ cd tmp
$ npm init -y
$ npm install @angular/cli@15
@angular/cli@15 を指定してインストールすることで Angular 15 を使用できる。
その後、hello-world プロジェクトを作成:
$ npx ng new hello-world --strict --skip-install
適当に質問にこたえると ./hello-world にプロジェクトのベースができている。 この ./hello-world 内で Angular アプリをつくっていく。
$ cd hello-world
$ npm install
$ npm start
http://localhost:4200 にブラウザでアクセスして作動を確かめます。
Hello, World! と表示するだけのアプリにつくりかえます。
現在のディレクトリがプロジェクトルート(./hello-world/) であるとして:
src/app/app.component.ts を次のようにする:
import { Component } from '@angular/core'
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Hello, World!'
}
src/app/app.component.html を次のようにする:
<div>{{title}}</div>
npm start して変更内容が反映できたか確かめます。
できた。
もう少し複雑なアプリにします。 フォームに名前を入れるとその名前を表示するだけのアプリです。
完成はこんなイメージ:
app.component.html をかきかえ:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Echo Server'
msg = ""
show = (yourname: string)=> { this.msg = yourname }
}
AppComponent クラスに msg と show を追加しました。
app.module.ts を次のように変更:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { CommonModule } from '@angular/common'
import { FormsModule } from '@angular/forms'
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule, CommonModule, FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
CommonModule と FormsModule を追加して imnports に加えただけです。
最後に app.component.html を変更します:
<div>{{title}}</div>
<div>
<input #yourname type="text" value="吉田兼好" size="16" />
<button type="button" (click)="show(yourname.value)">echo</button>
</div>
<div>{{msg}}</div>
input 要素に #yourname を書くと、それを button 要素で yourname.value のように参照できるようです。
npm run build してエラーがでなければ、 npm start して作動を確かめます。
起動時点ではこれ:
echo ボタンをクリックすると:
入力した名前(ここでは「吉田兼好」)がエコーされる。
かきかけです。