I'm using Angular 14, when I put this code, it works fine and the value is initialized.
<input type="text" name="name" value="John" >
But when I add ngModel, the value is no longer initialized, and nothing is showed in the text box.
<input type="text" ngModel name="name" value="John" >
How can I put a value in text box with ngModel ?
CodePudding user response:
MyComponent.component.html
<input type="text" [(ngModel)]="name" />
MyComponent.component.ts
...
class MyComponent {
public name = "Jhon";
}
And as you update the input, the variable name will be updated. If you dont want it updated just use [ngModel] instead of [(ngModel)]
CodePudding user response:
- Make sure you imported the
FormsModule from @angular/forms
- Use the banana box sintax,
[(ngModel)]="value"
or[ngModel]="value"
orngModel="value"
or(ngModel)="value"
base on what you want to achieve.
You can check the binding section of the Angular documentation to understand the differences:
https://angular.io/guide/binding-overview
CodePudding user response:
Try doing something like this instead
<input type="text" [(ngModel)]="varName">
<p>{{ varName }}</p>