Как вызвать ngModelChange, когда форма загружена с вводом по умолчанию - PullRequest
0 голосов
/ 11 марта 2020

У меня есть модал, который имеет 2 поля ввода. Метки выбора двигателя бронирования и названия тура появляются, когда выбран код тура. Идентификатор агента сам по себе является раскрывающимся списком.

Эта форма используется для создания и обновления, которое создает и обновляет строки в БД. Создать: работает нормально, проблем нет. Обновление: Код тура предварительно заполнен, и, следовательно, событие ngModelChange не вызывается для получения этих меток.

Есть ли способ получить запуск ngModelChange при вызове обновления?

component. html is:

<div class="modal-body">
    <form [formGroup]="tourFrom">
        <div class="form-group row">
            <label class="col-sm-4 col-form-label">Tour Code:</label>
            <div class="col-sm-8">
                <!--select formControlName="code" [(ngModel)]="tourcode" (ngModelChange)="tourCodeChanged($event)"-->
                  <select id="tour_code_select" formControlName="code"  (ngModelChange)="tourCodeChanged($event)">
                    <option *ngFor="let tourcode of alltournames | sortBy 'tourcode'" [value]="tourcode" > {{ tourcode }} </option>
                    <!-- <option *ngFor="let tour of tours" value="{{tour.code}}">{{tour.code}}</option> -->
                </select>
                <control-messages [control]="tourFrom.controls.code"></control-messages>
            </div>
        </div>   

        <div class="form-group row">
            <label class="col-sm-4 col-form-label">Reservation Engine Name :</label>
            <div class="col-sm-8">
                <label id="reservation_engine_label" ngDefaultControl formControlName="reservation_engine" *ngIf="tourcode">
                    <option *ngFor="let reservationEngine of filteredReservationEngines" [value]="reservationEngine.name"> {{ reservationEngine.name }} </option>
                    <!-- <option *ngFor="let tour of tours" value="{{tour.code}}">{{tour.code}}</option> -->
                </label>
                <control-messages [control]="tourFrom.controls.reservation_engine"></control-messages>
            </div>
        </div>


        <div class="form-group row">
            <label class="col-sm-4 col-form-label">Tour Name :</label>
            <div class="col-sm-8">
                <label id="tour_name_label" ngDefaultControl formControlName="tour_name" *ngIf="tourcode">
                    <option *ngFor="let tourname of filteredTourNames" [value]="tourname.name"> {{ tourname.name }} </option>
                    <!-- <option *ngFor="let tour of tours" value="{{tour.code}}">{{tour.code}}</option> -->
                </label>
                <control-messages [control]="tourFrom.controls.tour_name"></control-messages>
            </div>
        </div>
        <!--div class="form-group row">
            <label class="col-sm-4 col-form-label">Agent Name :</label>
            <div class="col-sm-8">
                <select formControlName="agent_name">
                    <option *ngFor="let agent of agents" value="{{agent.name}}">{{agent.name}}</option>
                </select>
                <control-messages [control]="tourFrom.controls.agent_name"></control-messages>
            </div>
        </div-->
        <div class="form-group row">
            <label class="col-sm-4 col-form-label">Agent Id</label>
            <div class="col-sm-8">
                <select formControlName="agent_id">
                    <option *ngFor="let agent of agents" value="{{agent.id}}">{{agent.id}}</option>
                  </select>            
                  <control-messages [control]="tourFrom.controls.agent_id"></control-messages>
            </div>
        </div>

component.ts is:

export interface MyClass {
  code: string
  name: string
}

@Component({
  selector: 'app-modal',
  templateUrl: './modal.component.html',
  styleUrls: ['./modal.component.scss']
})
export class ModalComponent implements OnInit {

  @Input() editTourData;

  tourFrom: FormGroup;
  public callUpdate : boolean = false;

  agents: any = [];
 // reservationEngines: any = ["resnet","jrs"];
  tours: any = [];
  private myclass: MyClass;
  tournames: Array<{ code: string, name: string }> = [];
  reservationEngines: Array<{ code: string, name: string }> = [];
  filteredTourNames: Array<{ code: string, name: string }> = [];
  filteredReservationEngines: Array<{ code: string, name: string }> = [];
  //tourcode: string;
  tourcode: any = [];
  code: any = [];





  constructor(public toastr:ToastrService,
    public activeModal: NgbActiveModal,
    public router: Router,
    public tourService: TouraccessService,
    public formBuilder: FormBuilder) { }

  ngOnInit() {
    console.log('edittourdata is', this.editTourData)
    if (this.editTourData != undefined && this.editTourData != null && this.editTourData.hasOwnProperty('tour_id')) {
      this.tourFrom = this.formBuilder.group({
        reservation_engine: [this.editTourData.reservation_engine],
        tour_name: [''],
        agent_id: [this.editTourData.agent_id, [Validators.required]],
        code: [this.editTourData.agent_product_code, [Validators.required]]
      });
      this.callUpdate = true;
    } else {
  //    console.log("this.editTourData is undefined");
      this.tourFrom = this.formBuilder.group({
        reservation_engine: [''],
        tour_name: [''],
        agent_id: ['', [Validators.required]],
        code: ['', [Validators.required]]

      });
    }


    this.getTours();
    this.getAgents();
    this.getTourNameByTourCode();
    this.getResEngineByTourCode();
    }

  get alltournames(): string[] {
    return this.tournames.map(tourname => tourname.code);
    console.log('alltournamesoutput is ', this.tournames)
  }

  get allreservationEngines(): string[]{
    return this.reservationEngines.map(reservationEngine => reservationEngine.code);
    console.log('allreseingines is ', this.reservationEngines)
  }


  getTours(){

      this.tourService.getToursList().subscribe(result => {
      console.log('result received ', result)
      this.tours =JSON.parse(JSON.stringify(result)).data;
    }, error => {
      console.log('error while fetching tour codes ', error)
      throw error

    });
  }

  getAgents() {
    this.tourService.getAgentList().subscribe(result => {
    this.agents = JSON.parse(JSON.stringify(result)).data;
      }, error => {
      console.log('error while fetching agent codes ', error);
      throw error;
    });
  }

  getTourNameByTourCode() {
    this.tourService.getTourNameByTourCode().subscribe(result => {
    this.tournames = result;
    return this.tournames;
    console.log('getTourNameByTourCode output is', this.tournames);

    }, error => {
      console.log('error while fetching agent codes ', error);
      throw error;
    });
  }

  getResEngineByTourCode() {
    this.tourService.getResEngineByTourCode().subscribe(result => {
    this.reservationEngines = result;
    return this.reservationEngines;
    }, error => {
      console.log('error while fetching reservationEngines ', error);
      throw error;
    });
  }

  tourCodeChanged(updatedTourCode: string) {
    this.filteredTourNames = this.tournames.filter(tour => tour.code === updatedTourCode); 
    this.filteredReservationEngines = this.reservationEngines.filter(tour => tour.code === updatedTourCode); 
  }



  public onOptionsSelected(event) {
    const value = event.target.value;
    var selected = value;
        console.log(value);
    return value;
  }

  /* ------------------------ ADD TOURS DATA ------------------------ */

  create() {
    console.log('create is called');
    if (this.tourFrom.valid) {
//      var resTemp = document.getElementById('reservation_engine_label').innerText;
      var data = {
        tourCode: this.tourFrom.value.code,
        resEngine: document.getElementById('reservation_engine_label').innerText,
        tourName: document.getElementById('tour_name_label').innerText,
        agentId: this.tourFrom.value.agent_id,
      }
      console.log('resEngine data is ' + data.resEngine);
      console.log('tourName data is ' + data.tourName);
      console.log('data is ' + data);

      if (data.resEngine.length > 0) {
        this.tourService.createTouraccess(data).pipe().subscribe(result => {
          console.log('result received from create api is ' + result);
          if (result['code'] == 200) {
            this.toastr.success(result['message'], 'Create Tour Access Data');
            this.activeModal.dismiss();
          } else {
            this.toastr.error(result['message'], 'Create Tour Access Data');
            $(".toast-container").css({ "z-index": "99999999999" });
          }
        }, error => {
          this.toastr.error(error, 'Create Herd');
          $(".toast-container").css({ "z-index": "99999999999" });
        });
      } else {
        this.toastr.error('Res Engine is empty. Its a new tour');
        $(".toast-container").css({ "z-index": "99999999999" });
        return;
      }
    } else {
      this.validateAllFields(this.tourFrom);
      //      console.log('else request data is ' + data);
      return;
    }
  }

  /* ------------------------ UPDATE TOURS DATA ------------------------ */
  update() {
    if (this.tourFrom.valid) {
      var resTemp = document.getElementById('reservation_engine_label').innerText;
      var data = {
        tourCode: this.tourFrom.value.code,
        agentName: this.tourFrom.value.agent_name,
        agentId: this.tourFrom.value.agent_id,
        oldAgentID: this.editTourData.agent_id
      }
      console.log('update tourdata is', data)
      if (resTemp.length > 0) {
        this.tourService.updateTouraccess(data).pipe().subscribe(result => {
          console.log('result received from backedn is ', result);
          if (result.code == 200) {
            this.toastr.success(result.message, 'Update Tour Access Data');
            this.activeModal.dismiss();
          } else {
            this.toastr.error(result.message, 'Update Tour Access Data');
            $(".toast-container").css({ "z-index": "99999999999" });
          }
        }, error => {
          this.toastr.error(error, 'Update Data');
          $(".toast-container").css({ "z-index": "99999999999" });
        });
      } else {
        this.toastr.error('Res Engine is empty. Its a new tour');
        $(".toast-container").css({ "z-index": "99999999999" });
        return;
      }
    } else {
      this.validateAllFields(this.tourFrom);
      return;
    }
  }

/* ------------------------ VALIDATE ALL FORM FIELDS ------------------------ */

  validateAllFields(formGroup: FormGroup) {
    Object.keys(formGroup.controls).forEach(field => {
        const control = formGroup.get(field);
        if (control instanceof FormControl) {
            control.markAsTouched({ onlySelf: true });
        } else if (control instanceof FormGroup) {
            this.validateAllFields(control);
        }
    });
  }
}
...