I have a template-driven form in MyFormComponent template
<div *ngIf="employee">
<h3>Employee {{employee.lastname}}</h3>
<form #f="ngForm" (ngSubmit)="submit(f)">
<div >
<label for="firstname">Name </label><br>
<input type="text" name="firstname" ngModel value="{{employee.firstname}}" >
</div>
<button type="submit">Update Employee Name</button>
</form>
The goal of the form is to update the name of a given employee.\
And the .ts file
import { Component, OnInit } from '@angular/core';
import { Employee } from '../employee';
import { NgForm } from '@angular/forms'
import { FormsModule } from '@angular/forms';
@Component({
selector: 'app-myform',
templateUrl: './myform.component.html',
styleUrls: ['./myform.component.css']
})
export class MyFormComponent implements OnInit {
public myvar = "hi";
constructor() {}
employee?: Employee;
ngOnInit(): void {
this.getEmployee();
}
submit(f: any){
//Everything here works correctly. I do get the form object
}
getEmployee(): void {
//Everything here works correctly
}
}
My problem is that the 'value' field is not showing in the app. It's blank/empty.
If instead of 'value' I use 'placeholder', it works. But I want it to be a default value there, so that the user doesn't have to type in if he does not want to change it.
If instead of {{employee.firstname}} I use 'myvar' which I declare public in the .ts file, it also does not show.
FormsModule is imported in root module.
@angular/cli 14.0.2. Mozilla/Chrome
CodePudding user response:
My suggestion is delete *ngIf="employee" in the top level div and use value="{{employee?.firstname}}" instead.
So:
<div >
<h3>Employee {{employee?.lastname}}</h3>
<form #f="ngForm" (ngSubmit)="submit(f)">
<div >
<label for="firstname">Name </label><br>
<input type="text" name="firstname" ngModel value="{{employee?.firstname}}" >
</div>
<button type="submit">Update Employee Name</button>
</form>
.
.
CodePudding user response:
You can try with given 2 approach.
1.
<form #f="ngForm" (ngSubmit)="submit(f)">
<div >
<label for="firstname">Name </label><br />
<input
type="text"
name="firstname"
[(ngModel)]="employee.firstname"
/>
</div>
<button type="submit">Update Employee Name</button>
</form>
<form #f="ngForm" (ngSubmit)="submit(f)">
<div >
<label for="firstname">Name </label><br />
<input
type="text"
name="firstname"
[value]="employee.firstname"
/>
</div>
<button type="submit">Update Employee Name</button>
</form>