关于javascript:Angular-里使用-FormControl-的步骤

4次阅读

共计 1775 个字符,预计需要花费 5 分钟才能阅读完成。

  1. 导入 FormControl:
import {FormControl} from '@angular/forms';

在 Component 里创立一个 name 实例,类型为 FormControl

name = new FormControl('Jerry');

通过构造函数 FormControl 设置初始值。

  1. 在 HTML 文件里,将 element 同 Component 的 name 属性建设绑定关系:

这之后 Component name 属性的值,就会主动传递到 HTML element 里:

这样,表单控件和 DOM 元素就能够相互通信了:视图会反映模型的变动,模型也会反映视图中的变动。

应用 .value 能够拜访 FormControl 实例的值:

<label for="name">Name: </label>
<input id="name" type="text" [formControl]="name">

<p> 显示控件的值: {{name.value}}</p>

如何应用 setValue 批改 FormControl 的值

updateName() {this.name.setValue('Nancy');
}

点击按钮之后:

值变为 nancy:

在 event handler 里看到 click 响应事件在 zone.js 里的对立解决:

最终在 core.js 里调用 executeListenerWithErrorHandling

执行 setValue:

如何响应用户输出

constructor(){
    this.name.valueChanges.subscribe(selectedValue => {console.log('value changed:', selectedValue);
    })
  }

成果:

从调用栈发现,依然是 executeListenerWithErrorHandling

通过 EventEmitter 发送更新:

ng-untouched ng-pristine ng-valid 这三个 class 什么时候赋的值?

  • ng-untouched The field has not been touched yet
  • ng-pristine The field has not been modified yet
  • ng-valid The field content is valid

如何应用表单组 form group

在 Component 里创立一个类型为 FormGroup 的属性。

其构造函数是一个 json 对象,property 的类型为 FormControl.

FormGroup 也能应用 setValue 等办法。

这个表单组还能跟踪其中每个控件的状态及其变动,所以如果其中的某个控件的状态或值变动了,父控件也会收回一次新的状态变更或值变更事件。

如何把 FormGroup 属性绑定到 HTML 文件中:

<form [formGroup]="profileForm">

  <label for="first-name">First Name: </label>
  <input id="first-name" type="text" formControlName="firstName">

  <label for="last-name">Last Name: </label>
  <input id="last-name" type="text" formControlName="lastName">

</form>

FormControlName 指令提供的 formControlName 属性把每个输入框和 FormGroup 中定义的 表单控件 绑定起来。
FormGroup 组内数据一样能够通过 valueChanges 被监控:

this.profileForm.valueChanges.subscribe(
      value => {console.log('group value:', value);
      }
    );

应用 setValue 批改 group 的值:

this.profileForm.setValue(
      {
        firstName: 'Tom',
        lastName: "Tom1"
      }
    );

form 标签所收回的 submit 事件是内置 DOM 事件,通过点击类型为 submit 的按钮能够触发本事件。这还让用户能够用回车键来提交填完的表单。

往表单的底部增加一个 button,用于触发表单提交。

onSubmit(){console.warn(this.profileForm.value);
  }
正文完
 0