我最近開始學習 Angular,但遇到了表單問題。我目前有一個帶有標簽和輸入欄位的表單。由于這是一個相當大的表單,我決定為表單的輸入和驗證制作一個單獨的組件。
因此,表格行如下所示:
<tr
app-table-row-input
[label]="'ConfigInterval'"
[formControl]="RestForm.controls['ConfigInterval']"
[type]="'number'"
></tr>
HTML 表格行輸入
<th>
<label class="required">{{ label }}</label>
</th>
<th>
<input
type="{{ type }}"
[ngClass]="{
'validation invalid': !ngControl.valid
}"
style="width: auto"
class="fullwidth"
[formControl]="ngControl.control"
required
/>
<span
class="validation-msg"
*ngIf="ngControl.invalid && (ngControl.dirty || ngControl.touched)"
>
Not valid
</span>
</th>
數字和文本的型別導致表單輸入被更新。但是,當我嘗試將其也用于復選框型別時,表單不會像不使用單獨組件時那樣更新為“true”或“false”。我的復選框代碼目前如下所示:
html父表單組件
<tr
app-table-checkbox
[label]="'AuthEnabled'"
[formControl]="RestForm.controls['AuthEnabled']"
[id]="'cb1'"
[type]="'checkbox'"
></tr>
html復選框輸入組件:
<th>
<label class="required">{{ label }}</label>
</th>
<th>
<input
type="{{ type }}"
class="fullwidth"
id="{{ id }}"
[formControl]="ngControl.control"
required
/>
<label for="{{ id }}">True or False</label>
</th>
兩個組件中的 TS 看起來相同(除了 id 屬性不存在):
export class TableCheckboxComponent implements ControlValueAccessor {
@Input() label: string;
@Input() type = 'text';
@Input() id: string;
constructor(@Self() public ngControl: NgControl) {
ngControl.valueAccessor = this;
}
writeValue(obj: any): void {}
registerOnChange(fn: any): void {}
registerOnTouched(fn: any): void {}
}
有人可以解釋為什么文本和數字輸入確實有效,但這不適用于復選框嗎?
uj5u.com熱心網友回復:
type="{{ type }}"最初是在輸入系結之后type="text"才解決的,這很糟糕。type="checkbox"ngControl.valueAccessor = this;
建構式在輸入系結到組件生命周期之前運行。
建議洗掉型別輸入TableCheckboxComponent并type="checkbox"直接放在input.
堆疊閃電戰
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/524415.html
上一篇:通過JS填充Angular表單
