如何在 Angular 中将此模板驱动的表单更改为反应式表单?

Posted

技术标签:

【中文标题】如何在 Angular 中将此模板驱动的表单更改为反应式表单?【英文标题】:How to change this template driven form to Reactive form in Angular? 【发布时间】:2022-01-23 09:43:36 【问题描述】:

如何将此模板驱动的表单更改为响应式表单?我想将此模板驱动的表单更改为反应式表单。我应该做哪些更改才能将其更改为 Reactive 形式?代码是完整的,不需要其他修改吗?有人可以帮我解决这个问题吗,我附上了所有必需的代码。在更改为响应式表单时我们应该记住哪些事项,以及为什么响应式表单优于模板驱动表单?

html 代码

 <html>
 <body>
   <nav>
       <div class = "navbar-header">
           <a href="#" class="navbar-brand">Image Change on clicking Enter in TextBox</a>
           <input class = "col" type = "text" readonly value ="imgNumber/3  cityImageId">
       </div>
    </nav>

<div class = "textarea" contenteditable #scrollDiv [scrollTop]="scrollDiv.scrollHeight" wrap="hard">
    <img contenteditable="false" [src]="imagePath" width = "1090px" height = "440"/>
</div>


<form>
    <div>
        <input type = "text" class="col2" [(ngModel)]="pincode" (keyup.enter)="generatecityDetailArray()" maxlength="6" [ngModelOptions]="standalone: true"/>
    </div>
</form>


<div>
    <input type = "label" class = "col3" value = "Pin Code" readonly />
</div>



 </body>
</html>

CSS 代码

    nav 
    background-color:black;
    border : 0;


.navbar-header
            text-align: center;

.navbar-header
    color:white;

.col
    margin-left: 950px;
    text-align: right;
    border : 0;
    background-color:rgb(160,0,0);


.textarea
    overflow: scroll;
    height: 400px;
    width:1090px;
    background-color:white;
    margin-left: 100px;
    margin-top: 50px;

     object-fit: none;
     object-position: 1000px 200px;


.col2
    width:230px;
    height: 30px;
    margin-top: 20px;
    margin-left: 950px;


.col3
    width:230px;
    height: 30px;
    margin-top: 20px;
    margin-left: 950px;

TypeScript 代码

    import  Component, OnInit  from '@angular/core';
import  CityClassificationService  from 'src/app/service/city-classification.service';

@Component(
  selector: 'app-city-classification',
  templateUrl: './city-classification.component.html',
  styleUrls: ['./city-classification.component.css']
)
export class CityClassificationComponent implements OnInit 
  imgNumber : number =-1;
  cityImageId : number = -1;
  imagePath : string ='';
  pincode:string='';
  curImageNumber:number=0;
  imageDetails:imageName:string,cityImageId:number,imgNumber:number[]=[];
  
 cityDetailArray : pincode : string; cityImageId : number; imgNumber:number;[] = [];
  
 

 constructor(private cityService:CityClassificationService)  
 
 ngOnInit(): void 
   this.imageDetails=this.cityService.getImageObject();
    this.getNextImage(this.imageDetails[this.curImageNumber]);
  

  getNextImage(imageObj:imageName:string,cityImageId:number,imgNumber:number):void
    this.imgNumber= imageObj.imgNumber;this.imagePath=`assets/images/$imageObj.imageName.png`;this.cityImageId=imageObj.cityImageId;
  

  generatecityDetailArray():void
    if(this.pincode=='' || this.pincode.toString().length>6)alert('Enter Valid PinCode');return;;
    this.cityDetailArray.push(
      pincode:this.pincode, cityImageId:this.cityImageId, imgNumber:this.imgNumber
    );
    this.pincode='';
    this.curImageNumber++;
    if(this.curImageNumber==this.imageDetails.length)this.submitForm();return;
    this.getNextImage(this.imageDetails[this.curImageNumber]);
  

  submitForm()
    //TODO here....
    this.cityService.getAPi(this.cityDetailArray);
  


模型类

export class CityClassification
  
    pinCode : string;
    cityImageId : number;
    imgNumber:number;
   
    constructor(pinCode : string, cityImageId : number,imgNumber:number)
        this.pinCode = pinCode;
        this.cityImageId = cityImageId;
        this.imgNumber = imgNumber;
    
   

服务类

import  Injectable  from '@angular/core';

@Injectable(
  providedIn: 'root'
)
export class CityClassificationService 
  imageDetails:imageName:string,cityImageId:number,imgNumber:number[]=[
    imageName:'Ghazipur1',cityImageId:101,imgNumber:1,
    imageName:'Nashik2',cityImageId:102,imgNumber:2,
    imageName:'Noida3',cityImageId:103,imgNumber:3
    
  ]

 
  constructor()  


  getAPi(formBody:any)
    //API TO SUBMIT FORM.....
    console.log('INSIDE SERvice.......',formBody);
  

  getImageObject():any
    //API HERE TO GET IMAGE
    return this.imageDetails;
  


【问题讨论】:

您只需要更改 ngmodel 表单,并通过将表单控件替换为 ngmodel 输入来使其成为反应式 我试过了,我做不到。你能展示样品吗 当然让我为你写一个小sn-p plz,如果可能,请将此表单更改为反应式。我做到了,但我必须改变一切,我非常困惑 如果这对我的回答有帮助,请投票 【参考方案1】:

这里有一个简单的代码sn-p,

假设您的组件名称为 AppComponent,

import  Component  from '@angular/core';
import  
  FormBuilder,
  FormGroup,
  FormControl,
  Validators
 from '@angular/forms';

@Component(
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
)
export class AppComponent 
    title = '***-examples';
    declare MultipleSelect: any;
    textInputForm: FormGroup;

    get textInputControl() 
      return this.textInputForm.get('textInputControl') as FormControl;
    

    constructor(
      private fb: FormBuilder
    ) 
      this.textInputForm = new FormGroup(
        
          textInputControl: new FormControl('', [Validators.maxLength(6)])
          
      );
    

    ngOnInit() 
    

    onClick(): void
      // Just to show you that form can read the values,
      console.log(this.textInputForm.getRawValue());
    

您的 Html 可能如下所示,

<form>
  <label>
    Input Name: 
    <input type="text" class="col2" [formControl]="textInputControl" maxLength="6"/>
  </label>
</form>

<button (click)="onClick()">Click</button>

【讨论】:

以上是关于如何在 Angular 中将此模板驱动的表单更改为反应式表单?的主要内容,如果未能解决你的问题,请参考以下文章

在 Oracle 中将过程更改为视图

如何在反应离子应用程序中将 ios 键盘返回按钮更改为下一步/完成?

在 Rails 中将 redirect_to 格式更改为 :js

在 PHP 中将 " 更改为 ' - HTML 表单

Angular2嵌套模板驱动表单

带有 ngFor 输入的 Angular 2 模板驱动表单