Angular is built in such a way to keep the form model and data model separate.
From the documentation:
In keeping with the reactive paradigm, the component preserves the immutability of the data model, treating it as a pure source of original values. Rather than update the data model directly, the component extracts user changes and forwards them to an external component or service, which does something with them (such as saving them) and returns a new data model to the component that reflects the updated model state.
But if you want to bind to a data model inside of a form, you can set ngModelOptions standalone to true
standalone: Defaults to false. If this is set to true, the ngModel will not register itself with its parent form, and will act as if it's not in the form. This can be handy if you have form meta-controls, a.k.a. form elements nested in the tag that control the display of the form, but don't contain form data.
Stack Blitz Example
In this example, the model has 3 fields, 2 of which can be edited on the form.
model.ts
export class Model {
fieldOne: string;
fieldTwo: string;
fieldThree: string;
constructor(fieldOne: string, fieldTwo: string, fieldThree: string)
{
this.fieldOne = fieldOne;
this.fieldTwo = fieldTwo;
this.fieldThree = fieldThree;
}
}
app.component.ts
import {Component, OnInit} from '@angular/core';
import {AbstractControl, FormBuilder, FormGroup} from '@angular/forms';
import {Model} from './model';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
private _form
private _model: Model;
get form(): FormGroup {
return this._form;
}
get model(): Model {
return this._model;
}
set model(model: Model) {
this._model = model;
}
constructor(private formBuilder: FormBuilder) {}
ngOnInit() {
this.model = this.newModel();
this.createForm();
}
private newModel(): Model {
return new Model('fieldOne', 'fieldTwo', 'fieldThree');
}
private createForm() {
this._form = this.formBuilder.group({
});
}
}
app.component.html
As the form values change, the actual data model is updated and only editable fields have been exposed to change via the form.
<form [formGroup]="form">
<div>
<label for="fieldOne">Field One</label>
<input
id="fieldOne"
type="text"
[(ngModel)]="model.fieldOne"
[ngModelOptions]="{ standalone: true }">
</div>
<div>
<label for="fieldTwo">Field Two</label>
<input
id="fieldTwo"
type="text"
[(ngModel)]="model.fieldTwo"
[ngModelOptions]="{ standalone: true }">
</div>
</form>
<h3>Model</h3>
<pre>{{ model | json }}</pre>