LoginSignup
4
4

More than 5 years have passed since last update.

[Angular] 自作したカスタムコンポーネントのフォームに双方向データバインドする

Posted at

子コンポーネントとの双方向データバインドに関して、基本的にはこちらの記事が参考になるのですが、私の場合は親コンポーネントの変数を、子コンポーネントのさらにform要素に双方向バインドしたいという要件がありましたので、メモします。
下記の通りsetter/getterを使用して実装できます。

こちら↓の記事を参考にしました。
TWO-WAY DATA BINDING IN ANGULAR

親コンポーネント

app.component.html
<app-custom [(modelAssess)]="{任意の変数}"></app-custom>

子コンポーネント

custom.component.ts
export class CustomComponent implements OnInit {

  private _model: any = null;

  @Input() get modelAccess() {
    return this._model;
  }

  @Output() modelAccessChange = new EventEmitter();
  set modelAccess( value ) {
    this._model = value;
    this.modelAccessChange.emit( this._model );
  }
}
custom.component.html
<input [(ngModel)]="modelAccess"></input>
4
4
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
4
4