简体   繁体   中英

Angular 5 ngModel doesnt update value

So 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 doesnt update the selectedComponent.title variable

Can anyone tell me whats going on?

使用双向绑定

 [(ngModel)]="selectedComponent.title"

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

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';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM