Angularのメモです!
もっと詳しくちゃんと書いてくださっている方がいるので、こちらを参考にしてください笑
コンポーネント
1つのコンポーネントを構成するファイルは
.html
.css
.component.ts (typescript)
.module.ts
の4つ。
.component.tsファイルに「ボタンクリック」などのイベントに対する処理を記述していく。
.module.tsファイルは、「コンポーネントのモジュール化」をするらしい。
コンポーネントの階層構造
コンポーネントの一番上の階層はapp.module.ts
→bootstrapに、AppComponentを指定することで、最初に呼び出されるコンポーネントを指定。
(「ぶーとすとらっぷ」って色んなところで使われる言葉だなぁ。)
ダブルカーリープレイシス
{{ 変数名 }}
→ユーザーの情報などを動的に表示できる。
.component.tsファイルのComponentクラスで定義した変数を表示できる。
- 変数の種類
let→変数:後で変更できる
const→定数:後で変更できない
typeScriptのコンポーネントクラスの中では、
let,constなどの変数の型を定義する必要はない。
→関数の中では必要。
constructorは各コンポーネントが呼ばれたときに走る関数。
→this.関数名で他の関数を呼び出すことができる。this.変数名で変数を参照できる。
ボタンに連動して関数を走らせる。
①htmlでボタンを設置
②(click)属性にコンポーネントクラスで定義した関数(click)=関数名(変数)と指定。
↓
<button (click)="addToCart(product)">Buy</button>
みたいな
SPA
component.tsの@Componentのselector
で、指定した名前で、html上でコンポーネント(のhtml)を表示できる。
@Component({
selector: "app-product-details",
templateUrl: "./product-details.component.html",
styleUrls: ["./product-details.component.css"]
})
みたいな
router-outletタグを使うことによって、爆速でページの切り替えができる
→aタグのhrefをrouterLinkにすることによって実現
app.module.tsの
RouterModule.forRootにpathとcomponentを指定。
↓
RouterModule.forRoot([
{ path: '', component: ProductListComponent },
{ path: 'products/:productId', component: ProductDetailsComponent},
{ path: 'cart', component: CartComponent},
{ path: 'shipping', component: ShippingComponent},
])
みたいな
Array(配列)を使った表示
{{ 配列名[インデックス] }}
*ngForを使った表示
<div *ngFor="let student of students">
{{ student }}
</div>
Jsonオブジェクト
{
name: "名前",
gender: "性別",
age: "年齢",
}
みたいなのを配列にすれば、
students = [
{
name: "名前",
gender: "性別",
age: "年齢",
},
{
name: "名前",
gender: "性別",
age: "年齢",
},{
name: "名前",
gender: "性別",
age: "年齢",
}
]
<div *ngFor="let student of students">
<p>{{ student.name }}</p>
<p>{{ student.gender }}</p>
<p>{{ student.age }}</p>
</div>
みたく、いい感じに表示できる。
プロパティバインディング
.component.tsファイルの値をhtmlにわたす.
[ 変数名 ] →角括弧[]
イベントバインディング
htmlのイベントを.component.tsにわたす.
( イベント名 ) →丸括弧()
*ngIf
<a *ngIF="product.description">
Description: {{ product.description }}
</a>
的な感じで、ある要素があるときにだけ表示する、などできる。
変数の型
変数名:型;
で宣言。
指定のないときは、
any型になる。
新しい変数の型(?)をつくりたいときは
型名.model.ts
みたいなファイルを作って、
export class 型名{
変数名:型名
...
}
みたいにクラスを作り、他のファイルでimportする。
変数名:型名[]
とすると、配列になる.
新規コンポーネントの作成
app直下に、
app/
└コンポーネント名
├ コンポーネント名.component.ts → @Component
├ コンポーネント名.component.css
└ コンポーネント名.component.html
を作って、
app.module.tsにインポートして、declearationsに登録する。
コンポーネントの中にコンポーネントを配置していくことで、階層化できる。
-
プロパティバインディング
作ったcompentにプロパティを渡すには、
htmlで、
<コンポーネント名 [変数名]="親コンポーネントの変数" >
~いろいろ~
</コンポーネント名>
tsで、
export class コンポーネント名{
@Input() 変数名;
}
とすればよい。
-
イベントバインディング
作ったコンポーネントからイベントを受け取る.
ボタンの場合、htmlで
<button (click)="onNotify.emit()"></button>
tsで
@Output() onNotify = new EventEmitter()
とする。
親コンポーネントのhtmlで、
(onNotify)="notify()"
tsで
notify関数を定義
する。
- 双方向バインディング
[()]
まとめ
コンポーネントを使うことで、ソースコードがシンプルになって、わかりやすくなるらしい。
フレームワークは奥が深いなぁ。