выбрав несколько значений с помощью флажка и отправив их в базу данных, используя formControlName в угловых 6 - PullRequest
0 голосов
/ 13 ноября 2018

Я хочу получить проверенные значения в дБ, используя formControlName.

.html файл;

<form id="student-form" [formGroup]="studentForm" (ngSubmit)="onsave(studentForm.value)"> <div class="container">
<div class="row">      
  <div class="col-xs-12 col-sm-10 col-md-8 col-lg-6 col-sm-offset-1 col-md-offset-2 col-lg-offset-3" id="personalDetails">
    <div class="form-group col-lg-12" style="margin:10px 0 20px; padding: 0px">
      <h4 style="text-align:center; padding:15px 0px; background-color:lightgreen; font-weight: bold">Personal Details</h4>
    </div>
    <hr>
    <div class="form-group col-sm-6 col-md-6 col-lg-6 clearfix" style="padding-left: 0px">
      <label for="firstName">First Name</label>
      <input type="text" minlength="4" class="form-control textboxsize" formControlName="StudentFirstName" id="firstName" name="firstName" placeholder="First Name" required>
    </div>
    <!-- <div class="alert alert-danger" *ngIf="firstName.errors?.required && (firstName.dirty || firstName.touched)">
      First name is required.
    </div> -->
    <div class="form-group col-sm-6 col-md-6 col-lg-6 clearfix" style="padding: 0px">
      <label for="familyName">Family Name/ Surname</label>
      <input type="text" class="form-control textboxsize" formControlName="StudentLastName" id="familyName" name="familyName" placeholder="Family Name/ Surname"> </div>  <div class="form-group col-xs-12 clearfix" style="padding: 0px">
      <label for="preferredCountry">Preferred Country</label>
      <br><button type="button" class="btn btn-classic" onclick="tgf()">Select Countries</button><br>
      <div class="col-xs-12 textboxsize" id="cl" style="display: none; border:0.5px solid #E0E0E0; border-radius:3px; margin-top: 5px; padding-left: 15px; max-width: 250px; max-height: 150px; overflow: scroll">

        <div class="checkbox" *ngFor="let country of selectCountries">

          <label>
            <input formControlName="PreferedCountry1" type="checkbox" [checked]="check" value="{{country.CountryID}}">
              {{country.CountryName}}
          </label>
        </div></div></div><div class="form-group col-xs-12" style="text-align:center;margin:5px auto 0px;">
      <div class="col-md-offset-0">
          <input id="btnPrevious" class="btn btn-success" value="Previous" name="btnPrevious" style="width: 100px; font-size: 18px; background-color: #009900;" onclick="myFunction()" />

          &nbsp;
           <!-- Store: [disabled]="F.invalid" -->
          <input id="btnRegister" type="submit" class="btn btn-success" value="Register" name="btnRegister" style="width: 100px; font-size: 18px; background-color: #009900;" />

      </div>       
    </div></div></div></form>

.ts file;

 studentForm:FormGroup; constructor(private _fb:FormBuilder, private httpService: HttpClient, 
private ser:ApiServiceService) {
this.studentForm = this._fb.group({ // Defining form controls which will be used in html
  "StudentFirstName":['', Validators.required,],
  "StudentLastName": ['', Validators.required,],
  "Contact":['', [Validators.required, Validators.pattern("[0-9]{10,}")]],
  "HighestEducation": ['', [Validators.required]],
  "EmailID1":['', Validators.required,],
  "StudentPassword": ['abc123', Validators.required,],
  "PreferedCountry1":['', Validators.required,],
  "CurrentInstitution": ['', [Validators.required]],
  "QuickCat_Name": ['', [Validators.required]],
  "QuickCourseName": ['', [Validators.required]],
  "countryisdcode": ['MY', Validators.required,],     
}); }  ngOnInit() { // making use of web API
this.httpService.get('url').subscribe(
  data => {
    this.selectCountries = data as string [];
  },
  (err:HttpErrorResponse) => {
    console.log(err.message);
  }
);

Я хочу отправить идентификаторы проверенных стран в db с помощью formControlName, "PreferredCountry1".Я получаю значение как true, если проверено, и false, если не проверено.

Спасибо:)

1 Ответ

0 голосов
/ 22 ноября 2018

Извините за опоздание.Я сам это сделал;

Я запустил функцию проверки флажка;

            <div id="foo" class="checkbox" *ngFor="let country of selectCountries">

              <label>
                <input type="checkbox" [checked]="check" id="uy" [value]="country.CountryID" name="countries" (change)="getCountries($event.target.value)">
                {{country.CountryName}}
              </label>
           </div>

В ".ts file";

`public getCountries(event): void{
var country = event;
console.log(typeof(country));
var i;
for (i = 0; i<15; i++) {
        if (this.selectCountries[i]["CountryID"] == country){
          var k = this.selectCountries[i]["CountryName"];
          if (this.SC.indexOf(k) !== -1){
            this.SC.splice(this.SC.indexOf(k), 1);
              console.log(this.SC);
          } else {
            this.SC.push(k);     
            console.log(this.SC);
          }
          if (this.SID.indexOf(country) !== -1){
            this.SID.splice(this.SID.indexOf(country), 1);
            this.countrys = JSON.stringify(this.SID);
            console.log(this.countrys);
          } else {
            this.SID.push(country);
            this.countrys = JSON.stringify(this.SID);
            console.log(this.countrys);
          }
        }
      }
    }
onsave(data){
  console.log(data);
  this.selectedCountries = this.SC.toString();
  this.studentForm.controls.PreferedCountry1.setValue(this.selectedCountries);
  this.ser.studentReg(this.studentForm.value).subscribe((res) =>{ 
  console.log(res); 
 });
}

`

Спасибо:)

...