18910140161

实现事件绑定,以便当用户在窗体上输入邮政编码时,它会根据输入的邮政编码自动填充城市

顺晟科技

2021-10-04 11:18:08

269

对Angular来说是非常新的,但我目前正在输入“邮政编码”后更新我的“城市”字段。getCityByZip函数将根据表单上的zip输入更改为city。onZipChange应该处理onchange事件。如有任何指导或帮助,将不胜感激。

profile-editor.component.ts

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


@Component({
  selector: 'app-profile-editor',
  templateUrl: './profile-editor.component.html',
  styleUrls: ['./profile-editor.component.css']
})
export class ProfileEditorComponent  {

  capstoneProposalForm = this.fb.group({
    contactName: ['', Validators.required],
    contactJob:  ['', Validators.required],
    contactEmail:  ['', Validators.required],
    contactPhone:  ['', Validators.required],
    orgName:  ['', Validators.required],
    orgAddress: this.fb.group ({
      street: ['', Validators.required],
      zip:  ['', Validators.required],
      city: [, Validators.required],
      state: ['', Validators.required]
    }),
    orgWebsite: ['', Validators.required]
    

  });

  ngOnInit(): void {
  }
  onSubmit() {
    // TODO: Use EventEmitter with form value
    console.warn(this.capstoneProposalForm.value);
  }
 
  onZipChange(){
    let postal_code = this.capstoneProposalForm.get('orgAddress')!.get('zip')!.value;
    this.getCityByZip(postal_code);
        
  }

  getCityByZip(zip: string){

    if (zip=="30144" || "30152"){
      this.capstoneProposalForm.setValue({
        orgAddress: {
          city: 'Kennesaw'
        }
      })
    }
    else if (zip=="30060" || "30061"|| "30062"|| "30063" || "30064" || "30065" || "30066" || "30067" || "30068" || "30069"){
      this.capstoneProposalForm.patchValue({
        orgAddress: {
          city: 'Marietta'
        }
      })
    }
    else if (zip=="30188" || "30189"){
      this.capstoneProposalForm.patchValue({
        orgAddress: {
          city: 'Woodstock'
        }
      })
    }
}
  
  constructor(private fb: FormBuilder) { }
}

下面是我的表单中包含事件的部分 profile-editor.component.html

<div formGroupName="orgAddress">
        <div>
        <label>Organization Address</label>
        </div>
        <label for="street">Street: </label>
        <input id="street" type="text" formControlName="street" required>

        <label for="zip">Zip Code: </label>
        <input id="zip" type="text" formControlName="zip"  (onchange)= "onZipChange()" required>
      
        <label for="city">City: </label>
        <input id="city" type="text" formControlName="city"  required >
      
        <label for="state">State: </label>
        <input id="state" type="text" formControlName="state" required>
      
      </div>
    </div>
    <div>
    <label for="orgWebsite">Organization Website: </label> 
    <input id="orgWebsite" type="text" formControlName = "orgWebsite" required>
    </div>

顺晟科技:

  • TAG:
相关文章
我们已经准备好了,你呢?
2024我们与您携手共赢,为您的企业形象保驾护航