1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

1. はじめに

今回は、Angular の基本的な操作のうち HTMLファイルに記述する部分 をいくつかまとめていきます。
今回Vueの時と同じ作りとしているため、是非こちらと比較してみると分かりやすいと思います。
【Vue.js】Vue.jsって何だろう(基本な操作(v-bind・{{ }}・v-on・v-model)編)
バージョンによって書き方の違いはありますが、私が使っているバージョン(Anuglar5)での書き方でご紹介します。

2. 基本的な書き方

概要

Angular では、コンポーネントは以下のように構成されます。
htmlファイル・tsファイル・cssファイルの3ファイル構成になります。

app.component.html

// 今回はここに書くことをまとめていきます。
<h1 [ngClass]="titleClass">{{ value }}</h1>
<button (click)="pushButton()">
  ボタンを押してください
</button>

app.component.ts

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

@Component({
  selector: 'app-root', // HTMLタグの名前
  templateUrl: './app.component.html', // HTMLテンプレート
  styleUrls: ['./app.component.css'] // スタイルシート
})

export class AppComponent {
  value: string = '';
  titleClass: string = 'title';

  // ボタンをクリックしたときの処理
  pushButton() {
    this.value = 'ボタンが押されました!';
  }
}

app.component.css

.title {
  color: red;
}

3.基本的な操作

①プロパティバインディング [ ]

HTML の属性に Angular のデータを動的に結びつける構文です。
Vue でいう v-bind に相当します。

<基本的な書き方>

sample.component.html

<!-- [属性名]="変数" -->
<img [src]="imageUrl">

** <説明> **
下記のコードだとsrcの値は静的(固定)であるため、常に "dog.jpg" しか表示されません。

 // srcは画像の場所(URL)を指定するタグです。
 <img src="dog.jpg">

下記のコードのようにプロパティバインディングを使うと** imageUrlのデータの中身を見て ** 、表示する内容を変えられるようになります。
(imageUrlの値が"dog.jpg" の場合は"dog.jpg"が、"cat.jpg"の場合は"cat.jpg"と動的に変化します。)

<!-- 変数に応じて変化 -->
<img [src]="imageUrl">

<テストコード>

sample.component.html

<img [src]="imageUrl" width="200">

<br><br>
<button (click)="changeImage()">画像を変える</button>

sample.component.ts

// ここ以降は次回以降解説します。
import { Component } from '@angular/core';

@Component({
  selector: 'app-sample',
  templateUrl: './sample.component.html'
})
export class SampleComponent {
  imageUrl = 'https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhG4xpQ_FMBOIdN_junRODMG3TxJw1q5hSm_OVtAJkeI_qS2JBSQbHltv1SE46v-zagGxHe6aKvzbkziOE7LeInDS7UIIhwUfcCBYnmFhJe6dNjM4Jribry1PoJagMXmVhOsR7ESGt-0l9G/s800/dog_akitainu.png';

  changeImage() {
    this.imageUrl = 'https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiRuu0RWoeHs26-kJWDLyILcJZ9OljBuc_LyatexrDqGsYOBKNqKJWrt_jKhFATb1jmj124nhh4vTprkPzcRYemzFuSxbCR9cGFomOZx-vnOwQ5a16_4TmbjRWUolmtkNHg_d_5h-BtyvoTMJCvJ6ZmiiiSyu_0RfsbAStBrMaoUm8HN6NFJHIi-Lv8f0hh/s790/bird_fukurou_run.png';
  }
}

ボタンを押すと、imageUrlの値が変更されるので、
image.png

から
image.png

へと画像が変わります!

②{{変数名 }}

Angular の中で定義した変数(=データ)を、画面に埋め込む(バインドする)ことができるコードです。
Vue の {{ 変数 }} と同じです。
プロパティバインディング[]と同様、変数の値が変更されると、{{ 変数名 ]}で表示される内容も変わります。

<基本的な書き方>

sample.component.html

<p>{{ message }}</p>

sample.component.ts

// 色々中略
 message = 'こんにちは、Angular!';

テストコードはイベントバインディング( )と統合します。

③ イベントバインディング ( )

ボタンをクリックするなどの 「ユーザーの操作」に反応して 処理を実行します。
Vueのv-onに相当します。

<基本的な書き方>

sample.component.html

<!-- (イベント名)="関数名()" -->
<button (click)="changeMessage()">クリック</button>

<テストコード>

app.component.html

<!-- メッセージ表示 -->
<p>{{ message }}</p>

<!-- ボタンをクリックすると、changeMessage が実行される -->
<button (click)="changeMessage()">メッセージを変更</button>

app.component.ts

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent {
  message = 'こんにちは!';

  changeMessage() {
    this.message = 'クリックされました!';
  }
}

ボタンをクリックをすると、
image.png

messageの値が変わる関数が実行されます。
image.png

④ 双方向バインディング [(ngModel)]

ユーザーの入力(フォームの値)とVueのデータを双方向(リアルタイム)に結びつける仕組みです。
Vue の v-model に相当します。
使うには FormsModule のインポートが必要です。

<基本的な書き方>

app.component.html

<input [(ngModel)]="text">
<p>{{ text }}</p>

<説明>
プロパティバインディング [ ]を使用した場合、 ユーザーが入力欄の値を変更しても、画面に変更後の値は表示されません。

app.component.html

<input [value]="text">

<!-- プロパティの値を表示 -->
<p>{{ text }}</p>

app.component.ts

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent {
  text = '入力前の値';
}

入力を変えても変わりません。
image.png

Angular の プロパティバインディング[] を使った場合、ユーザーが入力欄の値を変更しても、コンポーネント側のプロパティは更新されません。
これは「最初に値を渡すだけ」で、以降は反映を行わないためです。
コンポーネント → テンプレート という 一方方向のデータ流れ を「片方向バインディング」と呼びます。

<テストコード>

app.component.html

<!-- 双方向バインディング -->
<input [(ngModel)]="text">

<!-- プロパティの値を表示 -->
<p>{{ text }}</p>

app.component.ts

import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent {
  text = '入力前の値';
}

image.png

入力を変えると画面表示も変わるようになります。
image.png

一方で、Angular の [(ngModel)] を使用した場合は、ユーザーが入力欄の値を変更すると、コンポーネントのプロパティも更新されます。
つまり、テンプレートとコンポーネントの両方で変更が反映されます。
このようにデータ ↔ 画面表示のやり取りがリアルタイムで同期される仕組みを**「双方向バインディング」**と呼びます。

4.さいごに

その他にも色々できることがあるため、次回以降もhtmlタグ内に記述できることをまとめていきます。
ご興味ある方は次回以降も見ていただけると嬉しいです。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?