獲取響應式表單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);

  
  }
 

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM