To initialize a ngModel value in angular , Create a class Options like this:
Options.ts
export class Options {
location: string;
time: string;
constructor(location: string, time: string) {
}
}
Or
export class Options {
location: string;
time: string;
constructor(location: string, time: string) {
this.location = location;
this.time = time;
}
}
HTML:
<input type="text" name="location" [(ngModel)]="options.location" #location="ngModel" required/>
<input type="text" name="time" [(ngModel)]="options.time" #time="ngModel" required/>
And in your component initialize options like this:
options = new Options('','');
NOTE: if you create Options class like this:
export class Options {
constructor(location: string, time: string) {
}
}
It will work with ng serve but NOT with ng build --prod as AOT(Ahead-of-Time) compilation gives error:
ERROR in ng:/xxxx/x.component.html (67,74): Property 'location' does not exist on type 'Options'.
ERROR in ng:/xxxx/x.component.html (72,72): Property 'time' does not exist on type 'Options'.
If you initialize options in component in this way
options={};
will also gives same error.
options: {location: string};or the Angular 1 way you mentioned?this.options.location = "test"it saysthis.options is undefinedin the console...