微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

获取响应式表单FormGroup里的formControl对象示例

 获取FormGroup里的FormControl对象,通过FormGroup对象的get("FormControlName 名")

 

示例:

在根模块导入 

import { ReactiveFormsModule } from '@angular/forms';   @NgModule({   declarations: [     AppComponent,     HeroFormComponent,     FormcontrolComponent   ],   imports: [     browserModule,     AppRoutingModule,     FormsModule,     ReactiveFormsModule   ],   providers: [],   bootstrap: [AppComponent] })

 html文件

<form [formGroup]="fg" (ngSubmit)="onSubmit()">     username:<input type="text" formControlName="name"><br>     <select formControlName="selectName">         <option *ngFor="let item of list" [value]="item">{{item}}</option>     </select>     <button type="submit">提交</button> </form>   ts文件 import { Component, OnInit } from '@angular/core'; import { FormControl,FormGroup } from '@angular/forms'; @Component({   selector: 'app-formcontrol',   templateUrl: './formcontrol.component.html',   styleUrls: ['./formcontrol.component.css'] }) export class FormcontrolComponent implements OnInit {
  public list:Array<String>=["北京","天津","深圳"] //创建 FormGroup对象   public fg:FormGroup=new FormGroup({        name:new FormControl(""),        selectName:new FormControl("北京")   });   constructor() { }
  ngOnInit() {   } //获取FormGroup对象里的FormControl对象   name=this.fg.get('name');   onSubmit(){     //获取FormGroup对象里的FormControl对象   const selected=this.fg.get('selectName'); //打印FormControl 对象的值   console.log(selected.value); //打印FormControl 对象的值   console.log(this.name.value);
     }  
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐