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

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

问题描述

在 angular 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

推荐答案

简单说

反应式可用于以下情况

  • 具有更多字段的复杂表单.
  • 有多个复杂的验证.需要自定义验证
  • 要求将 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">

我们可以简单地显示用户在 UI 中给出的值.

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

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

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

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