0
votes

I'm trying to bind the model in angular template driven forms. I created a model class and using it to populate the input field.

HTML:

<div class="form-group col-md-2 col-12" [class.text- danger]="nameCode.invalid &&  nameCode.touched">
<label for="inputName"  class="form-control-label"> Name</label>
<input type="text" class="form-control" [class.is-form-invalid]="nameCode.invalid &&  nameCode.touched" id="inputName" name="lotCode"[(ngModel)]="formModel.name" #nameCode="ngModel" aria-describedby="nameHelp" autocomplete="new-password" required>
<small id="nameHelp" class="text-danger" *ngIf="nameCode.invalid && nameCode.touched">Required</small>

Component:

export class AppComponent  {
formModel: FormModel= new FormModel();
}
export class FormModel {
name: "abc"
}

https://stackblitz.com/edit/angular-yue9fe?file=src%2Fapp%2Fapp.component.ts

2
... and what is your question? Are you asking us to debug your code, because it does something other than you expect? If so, what does it do, and what do you expect instead?meriton
I would like to bind my input model with the formModel property and it doesn't work.User123

2 Answers

2
votes

name: "abc" should be name= "abc" (or name: string = "abc"). Right now you're declaring type of name as "abc", which is not what you want.

0
votes

You have bind the name as "abc" dataType. So if you want to bind your model with html you can define your formModel class like,

export class FormModel {
   constructor(public name="abc"){}
}