Angular выберите с помощью formcontrol - PullRequest
0 голосов
/ 06 апреля 2020

У меня есть образец формы, в который я отправляю данные и редактирую их, заполняя ту же запись в Форме, где я разработал форму с использованием FormGroup, и связываю значения с помощью методов API управления формой get (). Setvalue () для текстовые вводы, но я изо всех сил пытаюсь заполнить DropDowns (выбрать) при редактировании

Я использую эту строку для заполнения определенного раскрывающегося списка редактируемой записи, как показано ниже

this.form.controls [ 'p_county']. setValue (county [0] .county_id, {onlySelf: true});

<form [formGroup]="form">
    <div class="row">
        <div class="col-md-6">
            <div class="form-group">
                <label class="form-label">Country</label>
                <select class="form-control" formControlName="p_country">
                <option *ngFor="let element of country" [value]="element.country_id">{{element.country_name}}</option>
              </select>
                <span class="text-danger" *ngIf="f.p_country.touched && f.p_country.errors?.required">Please Select Country</span>
            </div>
        </div>
        <div class="col-md-6">
            <div class="form-group">
                <label class="form-label">State</label>
                <select formControlName="p_state" class="form-control" name="p_state">
                <option *ngFor="let element of state" [value]="element.state_id">{{element.state_name}}</option>
              </select>
                <span class="text-danger" *ngIf="f.p_state.touched && f.p_state.errors?.required">Please Select
                State</span>
            </div>
        </div>
        <div class="col-md-6">
            <div class="form-group">
                <label class="form-label">City</label>
                <select class="form-control" formControlName="p_city">
                <option *ngFor="let element of city" [value]="element.city_id">{{element.city_name}}</option>
              </select>
                <span class="text-danger" *ngIf="f.p_city.touched && f.p_city.errors?.required">Please Select City</span>
            </div>
        </div>
        <div class="col-md-6">
            <div class="form-group">
                <label class="form-label">County</label>
                <select class="form-control" formControlName="p_county">
                <option *ngFor="let element of county" [value]="element.county_id">{{element.county_name}}</option>
              </select>
                <span class="text-danger" *ngIf="f.p_county.touched && f.p_county.errors?.required">Please Select
                County</span>
            </div>
        </div>
        <div class="col-md-6">
            <div class="form-group">
                <label class="form-label">Zip Code</label>
                <input formControlName="p_zipcode" type="text" class="form-control" placeholder="Zip Code">
                <span class="text-danger" *ngIf="f.p_zipcode.touched && f.p_zipcode.errors?.required">Please enter Zip
                Code.</span>
            </div>
        </div>

    </div>
    <div style="text-align: center;">
        <button class="btn btn-primary" type="submit" (click)="addCompany()">Submit</button>
    </div>
</form>
      </div>

Я инициализирую форму, как показано ниже,

    form = new FormGroup({
    p_county: new FormControl('', Validators.required),
    p_country: new FormControl('', Validators.required),
    p_city: new FormControl('', Validators.required),
    p_state: new FormControl('', Validators.required),
    p_zipcode: new FormControl('', Validators.required),
    //usr_lname:new FormControl('', [Validators.required, Validators.email]),
  });

Моя функциональность здесь

getDDlistName(listname: string) {
    this.ddlist.getDDlist(listname).subscribe(response => {
      if (response.success) {
        this.ddlistname = response.data;
      } else {
        this.router.navigate(['/error']);
      }
    });
  }

  getStateDDList(code: string) {
    this.ddlist.stateDropDown(code).subscribe(response => {
      if (response.success) {
        this.state = response.data;
      }
      else {
        this.toastr.info('NO DD Data')
      }
    });
  }

  getCityDDList(code: string) {
    this.ddlist.cityDropDown(code).subscribe(res => {
      if (res.success) {
        this.city = res.data;
      } else {
        this.toastr.info('NO DD data', 'Client')
      }
    })
  }

  getCountyDDList(code: string) {
    this.ddlist.countyDropDown(code).subscribe(res => {
      if (res.success) {
        this.county = res.data;
      } else {
        this.toastr.info('NO DD data', 'Client')
      }
    })
  }

  getCountryDDList(code: string) {
    this.ddlist.countryDropDown(code).subscribe(res => {
      if (res.success) {
        this.country = res.data;
      } else {
        this.toastr.info('NO DD data', 'Client')
      }
    })
  }

  addCompany() {
    console.log('form', this.form)
    if (this.form.valid) {
      this.isSubmitted = true;
      this.gc.addCompany(JSON.stringify(this.form.value)).subscribe(response => {
        if (response.success) {
          if (this.form.controls['p_active'].value == false) {
            this.toastr.success('DeActivated Successfully', 'Client');
          }
          this.toastr.success('Saved Successfully', 'Client');
          this.router.navigate(['/default/adduser/search']);
          this.form.reset();
        }
        else {
          this.isSubmitted = false;
          this.toastr.error(response.errorMessage, 'Client');
        }
      });
    } else {
      // this.isSubmitted = false;
      this.toastr.error('Required Field information is not available. Please enter required information in highlighted fields as below.');
      this.validateAllFormFields(this.form);
    }
    return;
  }

  getCompanies() {
    this.getDDlistName("Company_Type");
    this.getStateDDList('ST');
    this.getCityDDList('CT');
    this.getCountyDDList('CY');
    this.getCountryDDList('CNT');
    let obj = localStorage.getItem('currentuser');
    this.allCompanies.p_comp_id = JSON.parse(obj).comp_id;
    this.allCompanies.p_level = 2;
    this.allCompanies.p_usr_id = JSON.parse(obj).usr_id;
    this.gc.getCompanies(this.allCompanies).subscribe(response => {
      if (response.success) {
        let data = response.data.filter(value1 => {
          if (parseInt(value1.comp_id) == parseInt(this.url[4])) {
            return value1;
          }
        });
        let type = this.ddlistname.filter(response => {
          if (response.dd_det_id == data[0].comp_type) {
            return response;
          }
        });

        let city = this.city.filter(value => {
          if (value.city_name == data[0].city_name) {
            return value;
          }
        })
        let county = this.county.filter(value => {
          if (value.county_name == data[0].county_name) {
            return value;
          }
        });

        let country = this.country.filter(value => {
          if (value.country_name == data[0].country_name) {
            return value;
          }
        });

        let state = this.state.filter(value => {
          if (value.state_name == data[0].state_name) {
            return value;
          }
        });
        this.form.get('p_zipcode').setValue(data[0].comp_zip);
        this.form.get('p_comp_address').setValue(data[0].comp_address);
        this.form.get('p_comp_address1').setValue(data[0].comp_address1);
        this.form.get('p_admin_pswd').setValue(data[0].usr_pswd);
        this.form.get('p_active').setValue(data[0].active);
        this.form.controls['p_state'].setValue(state[0].state_id, { onlySelf: true });
        //this.form.value.p_state = state[0].state_id;
        this.form.controls['p_comp_type'].setValue(type[0].dd_det_id, { onlySelf: true });
        //this.form.value.p_comp_type = type[0].dd_det_id;
        this.form.controls['p_city'].setValue(city[0].city_id, { onlySelf: true });
        //this.form.value.p_city = city[0].city_id;
        this.form.controls['p_country'].setValue(country[0].country_id, { onlySelf: true });
        //this.form.value.p_country = country[0].country_id;
        this.form.controls['p_county'].setValue(county[0].county_id, { onlySelf: true });
        //this.form.value.p_county = county[0].county_id;
        this.form.get('p_usr_id').setValue(JSON.parse(localStorage.getItem('currentuser')).usr_id);
      } else {
        this.toastr.error('Something went Wrong Pls Check System Admin', 'Client');
      }
    });
  }

1 Ответ

1 голос
/ 06 апреля 2020

У вас есть несколько проблем из того, что я вижу.

  1. Вы называете свою форму form в своем файле .ts и в своем html (<form [formGroup]="form">), но затем вы ссылаетесь на элементы управления формы в своем шаблоне. используя f. Если у вас нет получателя, которым вы не поделились, это вызовет у вас проблемы:
<!-- you need to reference `form.p_county.touched` instead of `f.p_county...` (unless you have a getter named `f`) -->
<span class="text-danger" 
  *ngIf="form?.p_country.touched && form?.p_country.errors?.required">
    Please Select Country</span>
В вашем .ts есть проблема asyn c. Ваши функции (getDDlistName(), getStateDDList(), getCityDDList(), getCountyDDList(), & getCountryDDList()) все делают асинхронные запросы своих данных. Это означает, что вам нужно дождаться завершения 1011 *, прежде чем пытаться получить доступ к данным, которые они устанавливают. Например, в вашем текущем коде у вас есть: getCompanies () { this.getDDlistName("Company_Type"); /* ... other code */ this.gc.getCompanies(this.allCompanies).subscribe(response => { if (response.success) { /* ... other code */ /* `this.ddlistname` is not guaranteed to have a value */ let type = this.ddlistname.filter(response => { if (response.dd_det_id == data[0].comp_type) { return response; } }); /* ... other code */ } Вам нужно изменить эти функции, чтобы они возвращали наблюдаемые, чтобы вы могли дождаться их завершения, прежде чем вызывать this.gc.getCompanies Изменить на что-то вроде этого: /* this needs to return the observable */ getDDlistName (listname: string) { return this.ddlist.getDDlist(listname) .pipe( /* use tap() to set `this.ddlistname` */ tap(response => { if (response.success) { this.ddlistname = response.data; } else { this.router.navigate(['/error']); } }) ); } /* do the same for getStateDDList(), getCityDDList(), getCountyDDList(), & getCountryDDList() */ /* change this to wait for all the requests before requesting gc.getCompanies() */ getCompanies () { let obj = localStorage.getItem('currentuser'); this.allCompanies.p_comp_id = JSON.parse(obj).comp_id; this.allCompanies.p_level = 2; this.allCompanies.p_usr_id = JSON.parse(obj).usr_id; /* these are all async, so you need to wait for them to complete */ /* forkJoin() will only emit a value when _all_ requests have finished */ forkJoin([ this.getDDlistName("Company_Type"), this.getStateDDList('ST'), this.getCityDDList('CT'), this.getCountyDDList('CY'), this.getCountryDDList('CNT') ]).pipe( /* once complete, switch to your getCompanies observable */ switchMap(arrayOfResults => { return this.gc.getCompanies(this.allCompanies) }) ).subscribe(response => { /* Note: this value here is the value from your `this.gc.getCompanies(this.allCompanies)` observable */ if (response.success) { /* ... other code */ Вы слишком много делаете, пытаясь установить значения ваших форм для новых данных. patchValue() - это функция, которую вы хотите использовать для обновления значения формы без очистки других значений формы. Кроме того, похоже, что вы пытаетесь установить значения формы, которых у вас нет (p_comp_address, p_comp_address1, p_admin_pswd). Я предполагаю, что вы просто не опубликовали эти поля формы в своем вопросе, но убедитесь, что у вас есть все эти поля формы в вашем шаблоне. Измените код на, чтобы значения выглядели так : getCompanies () { forkJoin([/* other code */]).pipe( /* once complete, switch to your getCompanies observable */ switchMap(arrayOfResults => { return this.gc.getCompanies(this.allCompanies) }) ).subscribe(response => { if (response.success) { /* other code */ let state = this.state.filter(value => { if (value.state_name == data[0].state_name) { return value; } }); /* once you have your values, use `patchValue()` to set them all at once */ this.form.patchValue({ p_country: county[0].county_id, p_state: state[0].state_id, p_city: city[0].city_id, p_county: county[0].county_id, }); /* any other code you want */ } else { this.toastr.error('Something went Wrong Pls Check System Admin', 'Client'); } }); } Вам может не понадобиться функция [compareWith], поскольку вы устанавливаете [value] в строку. Но не помешало бы держать его там.
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...