我在控制台中看到 ngmodel 已被弃用,并将在 Angular 7 上被删除。我有一个指令使用它来进行双向数据绑定(bind),我如何在没有 [(ngmodel)]
的情况下做到这一点?
import {Directive, ElementRef, HostListener} from '@angular/core';
@Directive({
selector: '[onlyFloat]'
})
export class OnlyFloatDirective {
private regex: RegExp = new RegExp(/^-?[0-9]+(\.[0-9]*){0,1}$/g);
private specialKeys: Array<string> = [ 'Backspace', 'Tab', 'End', 'Home', '-' ];
constructor(private el: ElementRef) {
}
@HostListener('keydown', [ '$event' ])
onKeyDown(event: KeyboardEvent) {
if (this.specialKeys.indexOf(event.key) !== -1) {
return;
}
let current: string = this.el.nativeElement.value;
let next: string = current.concat(event.key);
if (next && !String(next).match(this.regex)) {
event.preventDefault();
}
}
}
HTML:
<div class="ui-g-12 ui-md-6">
<label >Valor da Venda</label><br>
<input type="text" pInputText onlyFloat [(ngModel)]="produtoAgilForm.controls['ValorVenda'].value" placeholder="Valor Venda" formControlName="ValorVenda">
</div>
最佳答案
为了清楚起见,请注意 ngModel 仅在与 Reactive 表单一起使用时被弃用。这是一段时间以来的建议……但现在它在 v6 中已弃用,并将在 v7 中删除。
有关更多信息,请参阅文档的这一部分:https://angular.io/api/forms/FormControlName
如果在删除 ngModel 时删除了部分文档:
Support for using the ngModel input property and ngModelChange event with reactive form directives has been deprecated in Angular v6 and will be removed in Angular v7.
Now deprecated:
<form [formGroup]="form"> <input
formControlName="first" [(ngModel)]="value"> </form>
this.value = '一些值';
This has been deprecated for a few reasons. First, developers have found this pattern confusing. It seems like the actual ngModel directive is being used, but in fact it's an input/output property named ngModel on the reactive form directive that simply approximates (some of) its behavior. Specifically, it allows getting/setting the value and intercepting value events. However, some of ngModel's other features - like delaying updates withngModelOptions or exporting the directive - simply don't work, which has understandably caused some confusion.
以下是根据上述引用文档建议的更改:
To update your code before v7, you'll want to decide whether to stick with reactive form directives (and get/set values using reactive forms patterns) or switch over to template-driven directives.
After (choice 1 - use reactive forms):
<form [formGroup]="form">
<input formControlName="first">
</form>
this.form.get('first').setValue('some value');
然后回答你的问题......你不应该在这里需要 ngModel。您的绑定(bind)应该通过使用 formControlName
来处理。要设置值,请使用上面显示的代码。
您的指令不起作用吗?如果没有,您能否提供一个 stackblitz 来演示?
关于html - 没有 ngmodel 指令 Angular 两种方式数据绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51864313/