我對角度的形式有疑問。我的目標是制作一個填充了可以更改的默認值的表單。驗證表單后,它將資料發送到 MySQL 資料庫。
這是 component.html 代碼:
<form #adopt="ngForm" (ngSubmit)="success()">
<label for="email">Email:</label>
<input type="email" name="email" [(ngModel)]="adoptions.email" #email="ngModel">
<label for="animal">Twój wybór to:</label>
<input type="text" name="animal" [(ngModel)]="adoptions.animal" #email="ngModel">
<button [disabled]="adopt.form.invalid" type="submit">Adoptuj</button>
<button (click)="getAnimal('')" class="disable">Odznacz swój wybór</button>
</form>
這是打字稿代碼:
export class AdoptpageComponent implements OnInit {
adoptions = new Adoptions();
sessionValue
animal
value
msg='';
constructor(private userService: UserService, private shared: SharedService, private _service
: AdoptService, private _router : Router) {
}
ngOnInit(): void {
this.getUsers();
this.sessionValue = sessionStorage.getItem('email');
}
getAnimal(arg) {
this.animal = arg;
}
success() {
this._service.create(this.adoptions).subscribe(
data => {
console.log("dziala");
this._router.navigate(['/adopt'])
},
error => {
console.log("nie dziala");
this.msg = error.error;
}
)
}
}
我在上面發布的代碼有效,但只有當我從鍵盤將值輸入表單時。我希望以第一種形式自動檢索 sessionValue 中的值,并在第二種形式中自動檢索動物。當我輸入的不是 ngModel 時,我設法實作了它:
<input type="email" name="email" [value]="sessionValue" #email="ngModel">
但是隨后表單不起作用(它不會將資料發送到資料庫)。不幸的是,當兩者都使用時,[value] = "sessionValue" 不起作用
<input type="email" name="email" [value]="sessionValue" [(ngModel)]="adoptions.email" #email="ngModel">
您知道如何使用默認值提交表單嗎?
uj5u.com熱心網友回復:
首先:您正在系結adoptions.email和adoptions.animalto ngModel,但是當被觸發時它們是空的(甚至更糟 -null或undefined)ngOnInit,這就是您的輸入為空的原因。一旦您在輸入中引入文本,它們就會獲得價值,這就是您能夠成功執行的原因this._service.create
第二:您正在導致值系結沖突。的來源與ngModel的來源不同value。一旦ngOnInit被觸發value嘗試加載sessionValue輸入的值并ngModel嘗試加載任何內容,因為它的源是空的
value有的話就不用用了ngModel。您只需為其源變數設定起點值。像下面的例子
ngOnInit(): void {
adoptions.email = somehowGetEmail()
adoptions.animal= somehowGetAnimal()
}
如果您堅持使用ngModels.
但總的來說,這看起來像很多不必要的系結。由于這些是form inputs您應該使用的form's preimplemented features for value bindings. 檢查檔案的角度FormBuilder, formControl
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/481471.html
