How to create an Angular 7+ component with two way binding ?

You have an angular component, and would like to have a value with a two way binding similar to ngModel. The easiest way is to :

  • add an Input on your document
  • add an Ouput whose name is the one of the input, suffixed by Change (that’s a required naming convention)

For example :

@Component({
  selector: 'app-select-nature-document',
  template: './select-nature-document.component.html',
  styleUrls: ['./select-nature-document.component.css']
})
export class SelectNatureDocumentComponent implements OnInit {
  @Input()
  natureDocument: NatureDocument;
  @Output()
  natureDocumentChange: EventEmitter<NatureDocument> = new EventEmitter<NatureDocument>();
...

You can then notify the value change using the output event emitter :

  onNatureDocumentSelected() {
    this.natureDocumentChange.emit(this.natureDocument);
  }

And the component can be used like this :

<app-select-nature-document [(natureDocument)]="editedDocument.nature"></app-select-nature-document>

Thanks to https://stackoverflow.com/questions/42006770/angular2-component-input-two-way-binding.

Leave a Reply

Your email address will not be published. Required fields are marked *