Marc Rasmussen
Marc Rasmussen

Reputation: 20565

Angular 5 ngModel doesn't update value

I have the following component:

export class ModuleComponentComponent implements OnInit {
    dropzoneConf;
    fileService = environment.getFileUrl;

    constructor(
        private moduleComponentService: ModuleComponentService) {
    }

    @Input()
    selectedComponent: ModuleComponent;

    ngOnInit() {
        this.setDropZoneConfig();
    }    
}

And in that I have the following HTML:

<h3 class="m-portlet__head-text m--font-success">
   <input class="form-control" type="text" [ngModel]="selectedComponent.title" />
</h3>

and the way I add the component in my HTML:

<div class="col-lg-8 col-x1-12" *ngIf="selectedComponent != null">
   <app-module-component [selectedComponent]="selectedComponent"></app-module-component>
</div>

When I type something into the input field it doesn't update the selectedComponent.title variable

What might be going on?

Upvotes: 0

Views: 2336

Answers (3)

VAMSI AILA
VAMSI AILA

Reputation: 73

you should use two-way data binding

[(ngModel)]

<input class="form-control" type="text" [(ngModel)]="selectedComponent.title" />

and make sure to import forms module in app.module.ts

import { FormsModule } from '@angular/forms';

Upvotes: 2

Pterrat
Pterrat

Reputation: 1710

We need to use two way data binding with [(ngModel)]

<h3 class="m-portlet__head-text m--font-success">
   <input class="form-control" type="text" [(ngModel)]="selectedComponent.title" />
</h3>

You should read the part about two way data binding on Angular documentation

If you want to use [ngModel] only, you could but you have to catch changes with (ngModelChange)

<h3 class="m-portlet__head-text m--font-success">
   <input class="form-control" type="text" [ngModel]="selectedComponent.title" (ngModelChanges)="setTitle($event)" />
</h3>

You could improve it with forms, just ask me for any questions about that

Upvotes: 2

Sachila Ranawaka
Sachila Ranawaka

Reputation: 41445

Use the two way binding

 [(ngModel)]="selectedComponent.title"

Upvotes: 6

Related Questions