简体   繁体   English

angular 2在模板中获取FormControl作为局部变量

[英]angular 2 get FormControl in template as local variable

I use in angular 2 model driven forms,when the user leaves the input element i want update data in server immediately (autosave). 当用户离开输入元素时,我想在角度2模型驱动的表单中使用,我想立即更新服务器中的数据(自动保存)。

So, my solution is use the (blur) event and pass the form control to a function, then check the dirty property if is true, then update the server. 因此,我的解决方案是使用(blur)事件并将表单控件传递给函数,然后检查dirty属性是否为true,然后更新服务器。

How can I do this? 我怎样才能做到这一点?

Thanks in advance 提前致谢

  <input type="text" formControlName="firstName" [(ngModel)]="contact.firstName" #ctrl=[currentFormControl] (blur)="onBlur(ctrl)" /> 
frm.component.ts: frm.component.ts:

  onBlur(formControl: FormControl){ if(formControl.dirty){ //update server formControl.reset(); } } 

very simple 很简单

<form *ngIf="contactForm" (ngSubmit)="onSubmit()" [formGroup]="contactForm">
    <div class="col-sm-12">
        <div class="form-group col-sm-4">
            <input type="text"
                   formControlName="firstName"
                   [(ngModel)]="contact.firstName"
                   (blur)="onBlur(contactForm.controls['firstName'])"
            />
        </div>

I don't know what you mean by user lost control, but there is functionality built into angular router called CanDeactivate which allows you to stop navigation on any condition or to perform an action like saving data. 我不知道用户失去控制的意思,但是角度路由器内置了一项名为CanDeactivate的功能,该功能可以让您在任何情况下停止导航或执行诸如保存数据的操作。

Refer sample application here - angular.io/resources/live-examples/router/ts/plnkr.html 在此处参考示例应用程序-angular.io/resources/live-examples/router/ts/plnkr.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM