我已經用 Angular 構建了一個簡單的頁面,它從 web 服務獲取一些資料,將其放入變數中,并將它們顯示在文本框(和一個復選框)中,現在我需要將這些控制元件的值傳遞給一個函式單擊提交按鈕。我在網上找到了一些例子,但大多數要么不起作用,要么對于我作為初學者的需求來說太復雜了。
我在我的控制元件周圍添加了一個表單,如下所示:
<form #policydetails="ngForm" (ngSubmit)="onClickSubmit(policydetails)">
</form>
我已經添加ngModel到每個輸入控制元件。在我的 ts 檔案中,我有一個界面:
interface policyDetails {
surveyChecked: boolean;
title: string;
name: string;
address1: string;
address2: string;
address3: string;
address4: string;
address5: string;
postcode: string;
telephone: string;
telephone_work: string;
telephone_mobile: string;
email: string;
policy_no: string;
}
我的 onClickSubmit 函式如下所示:
onClickSubmit(policydetails: policyDetails) {
alert(policydetails.title);
}
這似乎應該可以作業,但是當我為網站提供服務時,我得到了這個:
Compiled with problems:X
ERROR
src/app/app.component.html:4:59 - error TS2345: Argument of type 'NgForm' is not assignable to parameter of type 'policyDetails'.
Type 'NgForm' is missing the following properties from type 'policyDetails': surveyChecked, title, address1, address2, and 9 more.
4 <form #policydetails="ngForm" (ngSubmit)="onClickSubmit(policydetails)">
誰能告訴我我做錯了什么?由于我對 Angular 很陌生,因此請盡量保持您的答案清晰和簡單。謝謝!
uj5u.com熱心網友回復:
我相信您可以洗掉 ="ngForm" 因為它是錯誤的語法,您可以為 policydetails 執行 #policydetails 作為您的 ID。嘗試這個
<form #policydetails (ngSubmit)="onClickSubmit()">
</form>
這將為您提供一個空表單,該表單不提交任何內容,然后您可以使用一些有角度的FormControl來跟蹤您的資料。您可以轉到 Angular 表單以獲取完整檔案。
uj5u.com熱心網友回復:
我不得不說我對此的反應有點失望,因為這對于 Angular 開發人員來說是一項如此基本的任務。無論如何,我自己設法找到了解決方案。我對表格做了一個小調整:
<form #policydetails="ngForm" (ngSubmit)="onClickSubmit(policydetails)">
</form>
至:
<form #policydetails="ngForm" (ngSubmit)="onClickSubmit(policydetails.value)">
</form>
我還必須從以下位置更改輸入:
<input type="text" value="{{ title }} " name="title" ngModel>
至:
<input type="text" [(ngModel)]="title" name="title" />
無論如何,感謝Zepse Wolf和Eliseo的嘗試。希望這可以幫助其他試圖掌握角度的人。
uj5u.com熱心網友回復:
對問題的回答有些要點(這只是出于好奇,因為最好的選擇是使用 [(ngModel)] 或 Reactive Forms
真的,您只能以 ngModel 的方式使用
<input name="first" ngModel required>
(不需要[(ngModel)])。
如果您想知道輸入是否被觸摸或有錯誤,您可以使用模板參考變數:
<input name="first" ngModel required #first="ngModel">
<span *ngIf="first.errors && first.touched">Required!!</span>
為了賦予價值,您可以使用自己的“ngForm”,例如
//get the ngForm
@ViewChild('policydetails',{static:true}) ngForm:NgForm
@ViewChild('policydetails') ngForm:NgForm
ngOnInit()
{
//it's necesary enclosed in a setTimeout because
//Angular "create the ngForm" after paint it
setTimeout(()=>{
this.ngForm.setValue({first:'first',last:'last'})
})
}
看堆疊閃電戰
但是,確實是在每個輸入中使用的好習慣[(ngModel)]
<input type="text" [(ngModel)]="first" name="title" />
而且,正如答案所示,如果我們使用 [(ngModel)],則永遠不要使用value(或者checked如果是復選框)。簡單地給變數賦值
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/496350.html
下一篇:列出所有洗掉任何檔案的git提交
