0

In Angular, how to make a custom component whose template is a simple have [(ngModel)] applied to it? I want this [(ngModel)] to be a simple boolean flag. This ngModel will then be changed upon clicking on the div. What is the minimum code to be added to the already existing component?

Vladimir Despotovic
  • 3,200
  • 2
  • 30
  • 58

1 Answers1

2

I don't really understand the need for [(ngModel)] If you want to two way bind a boolean into and out of your component, suggest the Angular Two-Way-Binding https://angular.io/guide/template-syntax#two-way-binding---

in your boolean flag case:

@Input()  flag: boolean| string;
@Output() flagChange = new EventEmitter<boolean>();
changeFlag() {
  this.flag = !this.flag;
  this.flagChange.emit(this.flag);
}

in the corresponting parent component you can use this property by the same syntax as [(ngModel)]:

[(flag)]

[(ngModel)] is sugar for [ngModel] property and (ngModelChange) event.

Daddelbob
  • 406
  • 4
  • 13