我有一个检索数字值的输入。我想更改html一侧的显示,基本上,如果变量等于7,则显示的值将变为'abcdefg'而不是7。相反,如果我键入abcdefg,我希望表格理解应该存储的值是7而不是字符串。有没有办法仅在HTML方面做到这一点?
<div class="col-6">
<mat-form-field>
<input matInput placeholder="Cardinality Max" required #asbiepCardinalityMax
(change)="changeMax(asbiepCardinalityMax.value)"
(focus)="focusInMax(asbiepCardinalityMax.value)"
[(ngModel)]="asAsbiepDetail().cardinalityMax"
(ngModelChange)="onChange()"
[disabled]="!isEditable() || !asAsbiepDetail().used"
(keypress)="numberOnly($event)">
</mat-form-field>
</div>
答案 0 :(得分:0)
您要分离出控制器的逻辑,以查看绑定和视图到控制器。您想要添加单独的功能以进行更新和阅读。您可以添加事件处理程序以设置值onChange并从ngModel中删除()(删除视图->控制器更新),也可以使用打字稿的getter和setter绑定到具有不同逻辑的一个值。
选项1:
HTML:
<div class="col-6">
<mat-form-field>
<input matInput placeholder="Cardinality Max" required #asbiepCardinalityMax
(change)="changeMax(asbiepCardinalityMax.value)"
(focus)="focusInMax(asbiepCardinalityMax.value)"
[ngModel]="fieldValue()"
(ngModelChange)="onChange()"
(change)="setFieldValue($event)"
[disabled]="!isEditable() || !asAsbiepDetail().used"
(keypress)="numberOnly($event)">
</mat-form-field>
</div>
控制器:
@Component({})
export class Controller {
realValue: number = 7;
setFieldValue($event) {
let newValue = $event.target.value;
//Code here to turn newValue into something correct for real value
if (newValue == 'abcdefg') {
realValue = 7;
}
}
fieldValue(): string {
if (realValue === 7) {
return 'abcdefg';
}
};
}
选项2:
HTML:
<div class="col-6">
<mat-form-field>
<input matInput placeholder="Cardinality Max" required #asbiepCardinalityMax
(change)="changeMax(asbiepCardinalityMax.value)"
(focus)="focusInMax(asbiepCardinalityMax.value)"
[(ngModel)]="fieldValue"
(ngModelChange)="onChange()"
[disabled]="!isEditable() || !asAsbiepDetail().used"
(keypress)="numberOnly($event)">
</mat-form-field>
</div>
控制器:
@Component({})
export class Controller {
realValue: number = 7;
set FieldValue(newValue): void {
//Code here to turn newValue into something correct for real value
if (newValue == 'abcdefg') {
realValue = 7;
}
}
get fieldValue(): string {
if (realValue === 7) {
return 'abcdefg';
}
};
}
然后在需要的地方使用realValue。
第一个优点是,您可以选择要触发哪个事件来触发在控制器上设置值的函数-您可能需要更改,键控,键控,模糊-您可以拥有任何经典的javascript事件。第二种方法需要onChange。