I'm trying to do a two-way binding between a 'user' variable and a form in the html template :
export class UsersComponent implements OnInit {
user: User = {
firstname: '',
lastname: '',
age: 0,
adress: {
street: '',
city: '',
state: ''
}
};
...
example from the form: (I don't want to paste a lot of code)
...
<div class="form-group">
<label for="street">Street Adress</label>
<input
type="text"
class="form-control"
[(ngModel)]="user.adress.street"
name="street"
/>
</div>
...
when I bind user.firstname, user.lastname or user.age it works: example :
[(ngModel)]="user.age" //works
but when I try user.adress.street, user.adress.city, or user.adress.state id does not compile example :
[(ngModel)]="user.adress.street" //does not work
but when I go to the interface User and I click save: the compilation works
export interface User{
firstname: string;
lastname: string;
age?: number;
adress?: {
street?: string,
city?: string,
state?: string
}
active?: boolean;
registered?: any;
hide?: boolean;
}
and when I edit the ts or the html file and I save: it gives me a compilation error :
Failed to compile.
src/app/components/users/users.component.html:39:36 - error TS2532: Object is possibly 'undefined'.
39 [(ngModel)]="user.adress.street"
~~~~~~
src/app/components/users/users.component.ts:7:16
7 templateUrl: './users.component.html',
~~~~~~~~~~~~~~~~~~~~~~~~
Error occurs in the template of component UsersComponent.
I tried using
user?.adress?.street
but it didn't work