2019年2月10日日曜日

Angular @ViewChild デコレーター

Angular では、HTML テンプレート上に定義されているコンポーネントを TypeScript 側から参照する機能として、@ViewChild デコレーターが提供されています。

例えば、AppComponent に次の MyLabelComponent を利用しているとします。


MyLabelComponent (TypeScript)
import { Component, Input } from '@angular/core';

@Component({
  selector: 'app-my-label',
  templateUrl: './my-label.component.html',
  styleUrls: ['./my-label.component.css']
})
export class MyLabelComponent {
  constructor() { }
  @Input('text') text: string;
}
MyLabelComponent (HTML テンプレート)
<p>
  my-label works! {{text}}
</p>

AppComponent の TypeScript 上で、@ViewChild デコレーターに型を指定するかたちで、MyLabelComponent を参照することができます。

AppComponent (TypeScript)
import { Component, ViewChild } from '@angular/core';
import { MyLabelComponent } from './my-label/my-label.component';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app1';

  @ViewChild(MyLabelComponent) myLabel: MyLabelComponent;

  getText() {
    console.log(this.myLabel.text);
  }
}

AppComponent (HTML テンプレート)
<app-my-label text="abc"></app-my-label>


なお、複数の MyLabelComponent が存在する場合、 テンプレート参照変数を利用してコンポーネントを特定します。(この例では、HTML テンプレート上の #label1 や #label2 がテンプレート参照変数です。)

 AppComponent (TypeScript)
export class AppComponent {
  title = 'app1';

  @ViewChild('label1') myLabel1: MyLabelComponent;
  @ViewChild('label2') myLabel2: MyLabelComponent;

  getText() {
    console.log(this.myLabel1.text);
    console.log(this.myLabel2.text);
  }
}

AppComponent (HTML テンプレート)
<app-my-label #label1 text="abc"></app-my-label>
<app-my-label #label2 text="def"></app-my-label>


Angular に関連するトピックは次のページにまとめてあります。

Angular 機能紹介一覧
https://kainobi2.blogspot.com/2019/02/angular.html

Angular @Input デコレーター

Angular の @Input デコレーターは、親コンポーネントから子コンポーネントに対してデータを渡す際に使います。

例えば、子コンポーネントとして MyLabel コンポーネントがあるとします。

MyLabel コンポーネント (TypeScript)
import { Component, Input } from '@angular/core';

@Component({
  selector: 'app-my-label',
  templateUrl: './my-label.component.html',
  styleUrls: ['./my-label.component.css']
})
export class MyLabelComponent {
  constructor() { }
  @Input('text') text: string;
}
MyLabel コンポーネント (HTML テンプレート)
<p>
  my-label works! {{text}}
</p>

 コンポーネントに text プロパティを定義し、更に @Input デコレーターを付与しています。外部コンポーネントからは、@Input デコレーターの引数に指定している 'text' というプロパティを利用して値を渡すことができるようになります。※ 引数を省略すると、変数名(ここでは 'text')というプロパティ名になります。

親コンポーネントからは次のように利用しています。 text というプロパティ(インプット)に対して "abc" という文字列を指定しています。

App コンポーネント(HTML テンプレート)
<app-my-label text="abc"></app-my-label>


Angular に関連するトピックは次のページにまとめてあります。

Angular 機能紹介一覧
https://kainobi2.blogspot.com/2019/02/angular.html

2019年2月9日土曜日

RxJS Observable の pipe メソッドが便利

タイトルのままです。pipe メソッドの中に map メソッドを挟んで処理を加えていく感覚がようやく分かってきました。使いこなせるようになりたいです。

参考サイト
http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html#instance-method-pipe

https://www.learnrxjs.io/operators/transformation/map.html

2019年2月7日木曜日

Netlify で Angular のルーティング利用時に必要な設定

Netlify に Angular のアプリケーションを配備しただけでは、Angular のルーティングが動作せずに 404 NotFound エラーが出ます。Netlify のサーバー上にファイルが見つからないためにこのエラーが出ているようです。エラーを解消して Angular のルーティングを動作させるためには、次の設定が必要でした。


1._redirects ファイルを作成します。
src フォルダ配下に "_redirects" という名前のファイルを作成します。


2._redirects ファイルの内容を加えます。(次の記述をコピペで OK です。)
/*    /index.html   200



3.angular.json の architect > build > options > assets に _redirects ファイルを指定します。

"architect": {
"build": {
"builder": "@angular-devkit/build-angular:browser",
"options": {
...
"assets": [
"src/favicon.ico",
"src/assets",
"src/_redirects",//←ここを追加
],

これで Angular のリダイレクトが正しく動作するようになります。


Angular に関連するトピックは次のページにまとめてあります。

Angular 機能紹介一覧
https://kainobi2.blogspot.com/2019/02/angular.html

2019年2月6日水曜日

Angular アプリケーションの PWA 化

Angular アプリケーションを PWA にする方法です。至って簡単で、次のコマンドを実行すると PWA になります。


ng add @angular/pwa --project=my-project  


my-project のところには、ご自身のプロジェクト名と置き換えて下さい。


Angular に関連するトピックは次のページにまとめてあります。

Angular 機能紹介一覧
https://kainobi2.blogspot.com/2019/02/angular.html

2019年1月27日日曜日

ASP.NET Core Web API クロスオリジンを許可する方法


Angular でちょっとしたサーバーとの通信をテストする時に、Cors エラーを回避するために使っています😅設定は簡単で、Startup.cs で UseCors メソッドを下記のように実装します。

public class Startup
{
    ...

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        // 追加
        app.UseCors(builder =>
         builder
         .WithOrigins("http://localhost:4200")
         .AllowAnyHeader()
         .AllowAnyMethod());

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseMvc();
    }
}

2019年1月15日火曜日

GitHub からコミットした履歴を消し去る方法

自分用のメモです。

最後のコミットを削除
git reset --hard HEAD~

結果をプッシュする
git push origin +master

2018年12月15日土曜日

GitBucket セットアップメモ

GitBucket のダウンロード
https://github.com/kohsuke/winsw/releases

winsw を遣って GitBucket をサービスとして登録する
https://github.com/kohsuke/winsw/releases

サービスの削除
sc delete gitbucket

2018年11月11日日曜日

Angular ngModel 使い方

Angular の ngModel の使い方をメモしておきます。黄色でハイライトされている部分を追加すると ngModel を利用できるようになります。

1.app.module.ts

ngModel は angular/forms の FormsModule に含まれているので、FormsModule をインポートします。また、NgModel デコレータの imports で FormsModule をインポートします。
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule }   from '@angular/forms';//追加

import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule//追加
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

2.app.component.html

HTML テンプレートで ngModel に変数 name をバインドします。
<input type="text" [(ngModel)]="name">
{{name}}

3.app.component.ts

変数 name の初期値を設定します。
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';
  name = 'sasaki';//追加
}

Angular に関連するトピックは次のページにまとめてあります。

Angular 機能紹介一覧
https://kainobi2.blogspot.com/2019/02/angular.html

2018年10月7日日曜日

ASP.NET Core Web API - html ファイルの利用

ASP.NET Core Web API で html ファイルを利用(表示)する方法です。

Startup.cs ファイルの Configure メソッドに、app.UseStaticFiles() を呼び出します。すると、wwwroot フォルダ配下の html ファイルを表示できるようになります。

public class Startup
{
    ...

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseMvc();
        app.UseStaticFiles(); //追加
    }
}

ASP.NET Core Web API - GET と POST

ASP.NET Core Web API で GET メソッドと POST メソッドの実装方法を調べてみました。


ValuesController.cs (一部抜粋)
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
    // GET api/values
    [HttpGet]
    public ActionResult<IEnumerable<string>> Get()
    {
        return new string[] { "value1", "value2" };
    }

    // POST api/values
    [HttpPost]
    public void Post([FromBody] string id)
    {
    }
}

index.html
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
</head>
<body>
    <input type="button" value="click" onclick="get()" />
    <input type="button" value="post" onclick="post()" />
    <script>
        function get(){
            var httpRequest = new XMLHttpRequest();
            httpRequest.onreadystatechange = function () {
                if (httpRequest.readyState === 4) {
                    if (httpRequest.status === 200) {
                        console.log("GET: 通信成功");
                    } else {
                        console.log("GET: 通信失敗");
                    }
                }
            };
            httpRequest.onload = function () {
                console.log("GET: 通信完了");
            };
            httpRequest.open("GET", "api/values", true);
            httpRequest.send(null);
        }

        function post() {
            var httpRequest = new XMLHttpRequest();
            httpRequest.onreadystatechange = function () {
                if (httpRequest.readyState === 4) {
                    if (httpRequest.status === 200) {
                        console.log("POST: 通信成功");
                    } else {
                        console.log("POST: 通信失敗");
                    }
                }
            };
            httpRequest.onload = function () {
                console.log("POST: 通信完了");
            };
            
            httpRequest.open("POST", "api/values", true);
            httpRequest.setRequestHeader('Content-Type', 'application/json');
            httpRequest.send(JSON.stringify("id=abc"));
        }
    </script>
</body>
</html>

POST を行うときには、setRequestHeader で Content-Type に application/json を指定する必要があります。ここが分からなくてしばらく調べました。

2018年9月22日土曜日

Flexbox を利用して要素を中央と右端に表示

Flexbox を利用して、要素を中央と右端に表示してみます。
parent クラスで display: flex としているので、justify-content に center とすることで、子要素(メインアイテム)を中央表示にしています。

item クラスで position: absolute としているので、子要素(メニュー)は 常に右端にくっついています。また、parent クラスで position: relative としているので、子要素(メニュー)は親要素の中で絶対位置の計算が行われます。

イメージ



CSS

<style>
    .parent {
        position: relative;
        display: flex;
        justify-content: center;

        border: black solid 1px;
        padding: 20;
    }

    .item {
        display: flex;

        margin: 3px;
        padding: 15px;
        border: black solid 1px;
    }

    .menu {
        position: absolute;
        right: 0;

        margin: 3px;
        padding: 15px;
        border: black solid 1px;
    }
</style>

HTML

<div class="parent">
    <div class="item">メインアイテム</div>
    <div class="item">メインアイテム</div>
    <div class="menu">メニュー</div>
</div>

2018年9月17日月曜日

JavaScript ネイティブの Promise を利用する方法

JavaScript ネイティブの Promise を利用する方法を調べてみました。備忘録のためメモしておきます。

処理が成功したら resolve メソッドを呼びます。処理が失敗したら、reject メソッドを呼びます。reject メソッドを呼ぶと、catch 句に入ります。

function myTest() {
  const promise = new Promise((resolve, reject) => {
      setTimeout(() => {
          console.log('スタート');
          //処理が成功したら、resolve を呼ぶ。
          resolve('1つ目の処理');
      }, 1000);

  });
  promise.then((message) => {
      return new Promise((resolve, reject) => {
          setTimeout(() => {
              console.log(message);
              resolve('2つ目の処理');
              //エラーの場合、resolve ではなく reject を呼ぶ。
              // reject('xxx');

          }, 300);

      })
  }).then((message) => {
      return new Promise((resolve, reject) => {
          console.log(message);
          console.log('3つ目の処理');
      })
  }).catch((error) => { // エラーの場合
      console.error('エラー', error);
  });
}