0
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?

More than 1 year has passed since last update.

[Angular] @Input,@Outputとちょっと@ViewChildについて

Posted at

@ Input

//@Input() property名:型;と定義する。

@Input()は、
子componentが親componentからの値を取得したい場合に使用します。

説明.
@Input()の使い方
【Paret側】
①htmlでChildcomponentのセレクタータグを記載。
 →下記例では、<app-child></app-child>
②childセレクタータグで、プロパティバインディング記載
 →[getValue]="$any(studyForm.get('memo'))"

補足1:getValueがChildcomponentで定義したInputデコレータpropertyです。

補足2:$any()は型チェックを一時的無視する意味を持ちます。
      型FormControlの値をbindingしようとすると型エラーとなり
    解決できなかったので使いました。

【Child側】
①@Input() property名:型;を定義します。

Parent.ts
  /**入力フォーム */
  studyForm = new FormGroup({
    startTime: new FormControl(''),
    endTime: new FormControl(''),
    category: new FormControl(''),
    memo: new FormControl(''),
    daily: new FormControl('')
  });
Parent.html
<app-child
  [getValue]="$any(studyForm.get('memo'))"
></app-child>

Child.ts
@Input() getValue:FormControl | undefined;
Child.html
<p>
  {{ getValue?.value }}
</p>

//補足: ?(オプショナルチェイニング)は、
//オブジェクトのプロパティが存在するかチェックしなく存在しなければundefinedを返す機能です。

@ Output

@Output() は、
子コンポーネントでイベント定義して、そのイベントが発火したときに
親コンポーネントで何らかの処理を実行したい際に利用する。

使用方法:
【Parent側】
①Childcomponentのセレクタータグを記載。
②イベントバインディングをセット。
 →
【Child側】
@Output() eventDD = new EventEmitter();を定義
②eventプロパティを変更する処理を実装する

Parent.html
<app-tChild (eventDD)="outputTest()"></app-tChild>
Parent.ts
  outputTest(){
    console.log("検知して親コンポーネントのmethodが実行された。");
  }

Child.html
特に不要
Child.ts
 //buttonタグclickで実行される。
  public submitClickForm(){
    console.log(this.studyForm.value);
    /**入力データグローバル変数保持処理 */
    this.topSerivce.variableSetting(this.studyForm.value);

    this.eventDD.emit("A"); //★
  }

@ViewChild()

@ViewChild()は、
親componentから子componentディレクティブまたは、
親componentからDOM要素へアクセスしたい際に利用する。

0
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
0
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?