Daniel Ellison
Daniel Ellison

Reputation: 1347

Angular 5 - Unable to 2 way bind data

I feel like this might be a basic question but after a week of doing research I cant figure out what I am messing up. Ill admit im not too comfortable with Angular (2++).

I am trying to create a simple CRUD system. I created a button on each row of my data table and added click events for each. This event will call a function on my service that would redirect me to the my form and populate my var CurrentIncident with its data. So far so good everything is connected great and I see the data from my console as expected:

Example data returned:

{ description: "This is a test", data1: "Another test", data2: "Another test"}

Next step was to setup a 2 way bind on my form using NgModel. So I added this in my inputs.

<input placeholder="Description" value="" [(ngModel)]="CurrentIncident.Description">

But it returns with the error:

ERROR TypeError: Cannot read property 'Description' of undefined

Would anyone know where im messing up?

Button event:

<button mat-mini-fab color="accent" (click)="CrudService.Edit_Incident(this.params.data)">
    <mat-icon aria-label="Edit">description</mat-icon>
</button>

Service:

import { Injectable } from '@angular/core';
import { Incident_Model } from '../incident_model';
import {Router} from "@angular/router";

@Injectable()
export class CrudService {

    constructor(private router: Router) {}

    public CurrentIncident: Incident_Model[];

    public Edit_Incident(data) {
        this.CurrentIncident = data;
        this.router.navigate(['form'])
        console.log( this.CurrentIncident )
    }
}

Form:

<mat-form-field fxFlex="40">
    <input matInput placeholder="Description" value="">
</mat-form-field>

Upvotes: 1

Views: 85

Answers (1)

S&#233;bastien
S&#233;bastien

Reputation: 12139

In your CrudService class, CurrentIncident is expected to be an array, though it is not given any value in the constructor.

That's why in your template

[(ngModel)]="CurrentIncident.Description"

CurrentIncident is initially undefined.

On top of that, given that CurrentIncident is an array, it will not have a Description property. Given your sample data you might use something like

[(ngModel)]="CurrentIncident[0].description"

But only once your CurrentIncident has been initialized.

To prevent errors until is CurrentIncident initialized, you could use *ngIf

<input placeholder="Description" value="" [(ngModel)]="CurrentIncident[0].description" *ngIf="CurrentIncident">

Upvotes: 3

Related Questions