[英]Two way data binding without ngmodel directive angular
我在控制台中看到ngmodel已被棄用,並將在角度7上刪除。我有一個指令使用它進行雙向數據綁定,我怎么能用[(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。 這是一段時間的建議......但是現在它已在v6中棄用,並將在v7中刪除。
有關更多信息,請參閱文檔的這一部分: https : //angular.io/api/forms/FormControlName
如果在刪除ngModel時刪除了部分文檔:
在Angular v6中不支持將ngModel輸入屬性和ngModelChange事件與反應式表單指令一起使用,並且將在Angular v7中刪除。
現已棄用:
<form [formGroup]="form"> <input
formControlName="first" [(ngModel)]="value"> </form>
this.value = 'some value';
由於一些原因,這已被棄用。 首先,開發人員發現這種模式令人困惑。 看起來正在使用實際的ngModel指令,但實際上它是一個名為ngModel的輸入/輸出屬性,它在響應式表達式上簡單地近似(某些)其行為。 具體來說,它允許獲取/設置值和攔截值事件。 但是,ngModel的一些其他功能 - 比如延遲更新withngModelOptions或導出指令 - 根本不起作用,這可以理解地造成了一些混亂。
以下是上述參考文檔的建議更改:
要在v7之前更新代碼,您需要決定是否堅持使用響應式表單指令(以及使用反應式表單模式獲取/設置值)或切換到模板驅動的指令。
之后(選擇1 - 使用反應形式):
<form [formGroup]="form">
<input formControlName="first">
</form>
this.form.get('first').setValue('some value');
並回答你的問題......你不應該在這里需要ngModel。 您的綁定應該通過使用formControlName
來處理。 要設置該值,請使用上面顯示的代碼。
你的指令不起作用嗎? 如果沒有,你能提供一個stackblitz來演示嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.