角度2中的模板驱动形式和反应形式之间有什么区别 [英] What are the differences between template driven forms and reactive forms in angular 2

查看:74
本文介绍了角度2中的模板驱动形式和反应形式之间有什么区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在角度2中,模板驱动形式和反应形式之间的区别是什么.在哪种情况下,我们需要使用模板驱动形式和反应形式

In angular 2 what is the difference between the template driven forms and reactive form. In which situations we need to use the template driven forms and reactive forms

推荐答案

我们可以简单地说

活动表格可以在以下情况下使用

Reactive form can be used in the following situation

  • 具有更多字段的复杂表格.
  • 有多个复杂的验证.需要自定义验证
  • 要求将JSON结构与表单中的值一起发送.

我们可以使用"form.value"以结构化的方式获取整个表单

We can get entire form in a structured way by using "form.value"

如果我们有4个字段以响应形式填写名字,姓氏,电子邮件,电话号码.

If we have 4 fields First Name, Last Name, Email, Phone Number in reactive form.

HTML代码为

<form [formGroup]="form">
    First Name <input formControlName="firstName">
    Last Name <input formControlName="lastName">
    Email <input formControlName="email">
    Phone Number <input formControlName="phoneNumber">
</form>

我们可以从下面的表格中获取值

We can get the values from the form like below

{
"firstName": "FName",
"lastName": "LName",
"email": "test@123.com",
"phoneNumber": "123"
}

通过调用form.value,其中form是我们创建的FormGroup变量.

by calling form.value, where form is FormGroup Variable that we created.

模板驱动表单:使用简单表单时可以使用它.喜欢登录页面.用两种方式进行数据绑定.我们可以简单地从ui向变量分配值,反之亦然.

Template Driven Form : It can be used when using simple forms. Like login page. With the two way data binding. We can simply assign value to variable from ui and vice versa.

一个简单的例子是,如果我们为下面的输入提供双向绑定.

Simple example is if we are givng two way binding for the below input.

<input [(ngModel)]="username">

我们可以简单地在用户界面中显示用户提供的值.

We can simply display the value that user is giving in the UI.

<p>Hello {{username}}!</p>

这篇关于角度2中的模板驱动形式和反应形式之间有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆