我在 MyFormComponent 模板中有一個模板驅動的表單
<div class="container" *ngIf="employee">
<h3>Employee {{employee.lastname}}</h3>
<form #f="ngForm" (ngSubmit)="submit(f)">
<div class="form-group">
<label for="firstname">Name </label><br>
<input type="text" class="form-control" name="firstname" ngModel value="{{employee.firstname}}" >
</div>
<button class="btn" type="submit">Update Employee Name</button>
</form>
表單的目標是更新給定員工的姓名。\
和 .ts 檔案
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
}
}
我的問題是應用程式中沒有顯示“值”欄位。它是空白/空的。
如果我使用“占位符”而不是“價值”,它會起作用。但我希望它是那里的默認值,這樣用戶如果不想更改它就不必輸入。
如果不是 {{employee.firstname}} 我使用我在 .ts 檔案中宣告為 public 的“myvar”,它也不會顯示。
FormsModule 在根模塊中匯入。
@角/cli 14.0.2。Mozilla/Chrome
uj5u.com熱心網友回復:
我的建議是在頂級 div 中洗掉 * ngIf="employee"并改用value="{{employee?.firstname}}"。
所以:
<div class="container">
<h3>Employee {{employee?.lastname}}</h3>
<form #f="ngForm" (ngSubmit)="submit(f)">
<div class="form-group">
<label for="firstname">Name </label><br>
<input type="text" class="form-control" name="firstname" ngModel value="{{employee?.firstname}}" >
</div>
<button class="btn" type="submit">Update Employee Name</button>
</form>
.
.
uj5u.com熱心網友回復:
您可以嘗試使用給定的 2 方法。
1.
<form #f="ngForm" (ngSubmit)="submit(f)">
<div class="form-group">
<label for="firstname">Name </label><br />
<input
type="text"
class="form-control"
name="firstname"
[(ngModel)]="employee.firstname"
/>
</div>
<button class="btn" type="submit">Update Employee Name</button>
</form>
<form #f="ngForm" (ngSubmit)="submit(f)">
<div class="form-group">
<label for="firstname">Name </label><br />
<input
type="text"
class="form-control"
name="firstname"
[value]="employee.firstname"
/>
</div>
<button class="btn" type="submit">Update Employee Name</button>
</form>
作業演示
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/496334.html
下一篇:使按鈕與另一個按鈕動態保持距離
