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?
Asked
Active
Viewed 236 times
1 Answers
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
-
what is sizeChange? – Vladimir Despotovic Sep 14 '18 at 08:24
-
pardon me, ofcourse it is "flagChange". Two way binding works as follows: you define an input variable and an output variable with the same name plus "Change": @Input() flag: boolean; @Output() flagChange = new EventEmitter
(); – Daddelbob Sep 14 '18 at 08:41