Reactive Forms Ionic 4, data call

Asked

Viewed 215 times

-1

I used ngModel to take data from an api and move to a form, where the user typed the zip code and obtained the data, but as it will be discontinued, I will switch to reactive Forms, now I’m having an error where it seems the data is zeroed after the search

import { Component, OnInit } from '@angular/core';
import { 
  Platform, 
  NavController,
  LoadingController
} from '@ionic/angular';

import { AuthService } from 'src/app/services/auth.service';
import { BackendService } from 'src/app/services/backend.service';
import { FormGroup, FormBuilder, FormControl, Validators} from '@angular/forms';


@Component({
  selector: 'app-new-account-cnpj',
  templateUrl: './new-account-cnpj.page.html',
  styleUrls: ['./new-account-cnpj.page.scss'],
})
export class NewAccountCnpjPage implements OnInit {
  dataCep: any = {logradouro: null, bairro: null, localidade: null}
  cnpj: any;
  dataCnpj: any;
  result: any;
  step: any = 1;
  delivery: any = -1;
  dataDelivery: any = {cep: null, logradouro: null};

  constructor(
  	private platform: Platform,
  	private authService: AuthService,
  	private backendService: BackendService,
  	private navCtrl: NavController,
    public loadingController: LoadingController,
    private formBuilder: FormBuilder
    ) {}
    public user={
      numero: '198'
    }
    
    
      public errorMessages={
      log:[
        { type: 'required', message: 'Digite o Logradouro' },
        { type: 'minLength', message: 'Mínimo 2 letras'},
        { type: 'maxlength', message: 'Máximo 50 letras' }        
      ],        

      num:[
        { type: 'required', message: 'Digite o Número' },
        { type: 'pattern', message: 'Número inválido'},
        { type: 'minLength', message: 'Mínimo 1 número'},
        { type: 'maxlength', message: 'Máximo 15 números' }        
      ],
      
      bai:[
        { type: 'required', message: 'Digite o Bairro' },
        { type: 'minLength', message: 'Mínimo 2 letras'},
        { type: 'maxlength', message: 'Máximo 50 letras' }        
      ],
    
    
      cid:[
        { type: 'required', message: 'Digite a Cidade' },
        { type: 'minLength', message: 'Mínimo 2 letras'},
        { type: 'maxlength', message: 'Máximo 50 letras' }       
      ],
      state:[
        { type: 'required', message: 'Digite o Estado' },
        { type: 'minLength', message: 'Mínimo 2 letras'},
        { type: 'maxlength', message: 'Máximo 50 letras' }        
      ]
    };

    ValidateForm = this.formBuilder.group({
      log: ['', [Validators.required, Validators.maxLength(50),Validators.minLength(2)]],
      num: ['', [Validators.required, Validators.pattern('[0-9]'), Validators.maxLength(15),Validators.minLength(1)]],
      bai: ['', [Validators.required, Validators.maxLength(50),Validators.minLength(2)]],
      cid: ['', [Validators.required, Validators.maxLength(50),Validators.minLength(2)]],
      state: ['', [Validators.required, Validators.maxLength(50),Validators.minLength(2)]]
    });
    

  ngOnInit() {
  }



  async getCEP() {
  	if(this.dataDelivery.cep.length == 9) {
	  	const loading = await this.loadingController.create({
	      message: 'Carregando',
	      translucent: true,
	      mode: 'ios'
	    });
	    loading.present().then( () => {
	    this.backendService.getCEP(
	        this.dataDelivery.cep,
	        async result => {
	          console.log('cep',JSON.stringify(result));
	          this.ValidateForm.value = result;
	          if(this.dataCep.erro == true) alert("CEP Inválido");
	          //if(this.dataCep.logradouro) this.step = 4;
	          await loading.dismiss();
	        },
	        async error => {
	          await loading.dismiss();
	          console.log(error);
	        }
	    );
	    });
	} else this.dataCep = {};
  }



   
<ion-item>
			  <ion-label position="stacked" class="component-title">CEP</ion-label>
			  <ion-input 
			  type="text" placeholder="Insira o CEP aqui" [brmasker]="{mask:'00000-000', len:9}"[(ngModel)]="dataDelivery.cep" (keyup)="getCEP()" type="tel"  pattern="[0-9]*"></ion-input>
			</ion-item>
  
		  <div *ngIf="ValidateForm.value?.logradouro">
		  <form [formGroup]="ValidateForm">

			  <ion-item>
					<ion-label position="stacked" class="component-title">Logradouro</ion-label>
					<ion-input type="text" placeholder="rua, avenida, rodovia" formControlName="log" ></ion-input>
			  </ion-item>
			  
  

			  <ion-item>
				  <ion-label  style= "font-size: 15px; font-weight: bold;" >Número</ion-label>			
					<ion-input type="text" placeholder="ex: 001" formControlName="num"></ion-input>
				  <p style="font-size: 14px;">sem número</p><ion-toggle></ion-toggle>
			  </ion-item>
			  
  
			  <ion-item>
					<ion-label position="stacked" class="component-title">Complemento</ion-label>
					<ion-input type="text" placeholder="bloco, apartamento" ></ion-input>
			  </ion-item>
			  
  
			  <ion-item>
					<ion-label position="stacked" class="component-title">Bairro</ion-label>
					<ion-input type="text" placeholder="bairro" formControlName="bai" ></ion-input>
			  </ion-item>
			  

  
			  <ion-item>
					<ion-label position="stacked" class="component-title">Cidade</ion-label>
					<ion-input type="text" placeholder="cidade" formControlName="cid" ></ion-input>
			  </ion-item>
			
  
			  <ion-item>
					<ion-label position="stacked" class="component-title">UF</ion-label>
					<ion-input type="text" placeholder="estado" formControlName= "state" ></ion-input>
			  </ion-item>
			  
			</form>
  
			  <div style="text-align: center;">
				<ion-button [disabled]="!ValidateForm.valid" color="secondary" (click)="setStep(5)">
				  Próximo
				</ion-button>
			  </div>
		  </div> 

in html, I use a *ngIf to display the cep data, after your query, but when I run, it runs for 1 second and the results disappear, with the following error:

Newaccountcnpjpage.html:133 ERROR Error: Expressionchangedafterithasbeencheckedefeat: Expression has changed after it was checked. Previous value: 'ngIf: Avenida Dom Paulo Rolim Loureiro'. Current value: 'ngIf: Undefined'.

1 answer

0

Validateform has no street, let only ! Validateform.Valid in if

Browser other questions tagged

You are not signed in. Login or sign up in order to post.