Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can ng-model update objects in the model?

I am trying to write a data entry with Angular 2 and Typescript, but I have a problem when updating the model. As I understood only primitive types can be bind to ng-model. But in my model I have objects which I want to be updated. Is there any angular specific way to do it instead of loading the hole object with the changed property which is bind to ng-model ?

This is the model:

export class Project {
    public id: number;
    private title: string;
    private region: Region;
}

This is the Angular Component class:

@Component({...})
export class ProjectForm {
    public project: Project;
    public regions: Array<Region>;
}

This is the view of the ProjectForm:

...
<select id="region" [(ng-model)]="project.region.id">
    <option *ng-for="#region of regions" [value]="region.id">
        {{ region.name }}
    </option>
</select>
like image 841
Anoush Hakobyan Avatar asked Sep 26 '22 02:09

Anoush Hakobyan


1 Answers

Yes! Objects' properties can be bound with ngModel. See Plnkr

Because,

<input [(ngModel)]="project.region.id" />

breaks down to

<input [ngModel]="project.region.id"  (ngModelChange)="project.region.id = $event" />

which is just same as

<input [value]="project.region.id" (input)="project.region.id = $event.target.value" >

So, as you can see it's just passing value from one place to another, that value (Primitive or Not) can be anywhere.

like image 51
Ankit Singh Avatar answered Sep 30 '22 07:09

Ankit Singh