Angular2 implements custom bi directional binding properties

  • 2021-08-05 08:38:58
  • OfStack

Organize the document, search out 1 Angular 2 to achieve custom bidirectional binding attributes of the code, a little streamlined to do under the sharing.


import { Component, OnInit, Output, Input, EventEmitter } from '@angular/core';

@Component({
  selector: 'twoway',
  template: `
    <input [(ngModel)]="username">
    <p>Hello {{username}}!</p>
  `
})
export class TwoWayComponent implements OnInit {
  constructor() { }

  usernameValue: string;
  @Output() usernameChange = new EventEmitter();

  @Input()
  get username() {
    return this.usernameValue;
  }
  set username(val) {
    this.usernameValue = val;
    this.usernameChange.emit(this.usernameValue);
  }

  ngOnInit() {

  }
}

When used, you can bind bidirectionally through [(username)] = "your current attribute". Attribute name + suffix Change is a fixed way of writing a convention.


Related articles: