ngModel creating an object property on null object

39 Views Asked by At

Currently I am experimenting with template driving forms in Angular 17, I have the object interfaces

interface test2 = {
    name : string
}

interface test = {
    name : string,
    another? : test2
}

and I am creating the object like

let obj : test = { name: "moo", another: null };

and then in the page I have a simple input

<input name="tester" [(ngModel)]="obj.another.name">

Which will crash and burn. Doing

<input name="tester" [(ngModel)]="obj.another && obj.another.name">

will allow it to display the page but not create the object when data is entered into the field. Is there anyway for Angular to create the object of test2 when the object is null and assign its value when data is entered in the field? This used to work in AngularJS.

This will allow me to set the objects to null unless someone has entered data.

Cheers

1

There are 1 best solutions below

3
Tortila On

You can do it like this:

<input name="tester" [ngModel]="obj.another?.name"
 (ngModelChange)="obj.another = $event ? { name: $event } : null">

Also you might need to change another? : test2 to another? : test2 | null.