Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { Component, OnInit, group, Directive } from '@angular/core';
- import { FormGroup, FormControl, Validators, FormArray } from '@angular/forms';
- import { Url } from 'url';
- import { Router, ActivatedRoute } from '@angular/router';
- import { TranslateService } from '@ngx-translate/core';
- import { Http, RequestOptions, RequestOptionsArgs } from '@angular/http';
- import { Headers } from '@angular/http';
- import { Observable } from 'rxjs/Observable';
- import { routerTransition } from '../../../router.animations';
- import { SystemUsersService } from '../../../shared/services/system-users.service';
- import { MaskService } from '../../../shared/services/mask-forms.service';
- import { UsersDocuments } from '../../../shared/models/system-users-documents';
- import { SystemUserUniversityTransportation } from '../../../shared/models/system-users-university-transportation.model';
- import { UniversityTransportation } from '../../../shared/models/universityTransportation.model';
- import { Institution } from '../../../shared/models/institution.model';
- import { NgbModal, ModalDismissReasons } from '@ng-bootstrap/ng-bootstrap';
- @Component({
- selector: 'app-university-transportation',
- templateUrl: './university-transportation-new.component.html',
- styleUrls: ['./university-transportation-new.component.scss'],
- animations: [routerTransition()]
- })
- /**
- * @class UniversityTransportationNewComponente
- * @description componente utilizado para cadastrar um novo usuário universitário
- */
- export class UniversityTransportationNewComponent implements OnInit {
- public token: string = localStorage.getItem('token');
- public daysOfTheWeek: Array<Object>;
- public institutions: String[] = ["Escolha uma instituição", "UFMS", "IFMS", "AEMS", "FUNEC", "FEA", "FIU", "FIRB"];
- public bloodTypes: String[] = ["Não sei informar", "A+", "A-", "B+", "B-", "AB+", "AB-", "O+", "O-"];
- public citysInstitution: String[] = ["Escolha uma cidade", "TRÊS LAGOAS - MS", "PEREIRA BARRETO - SP", "ANDRADINA - SP", "SANTA FÉ DO SUL - SP"];
- public phoneTypes: String[] = ["Tipo", "RESIDENCIAL", "CELULAR"];
- public timeToGoInstitution;
- public timeToBackInstitution;
- public visualizationPessoais: boolean = false;
- public visualizationEnd: boolean = false;
- public visualizationInsti: boolean = false;
- public visualizationDoc: boolean = true;
- public closeView: string;
- public localUrlRg;
- public localUrlCpf;
- public localUrlRes;
- public localUrlMat;
- public localUrlCad;
- public localUrlPhoto;
- public formNewUser;
- public classPersonalData = "is-current";
- public classAddress = "";
- public classInstitution = "";
- public classDocuments = "";
- public classSave = "";
- public textPersonalData = "Passo Atual:";
- public textAddress = "";
- public textInstitution = "";
- public textDocuments = "";
- public timeGoValid: number;
- public timeBackValid: number;
- public errorTable: boolean = false;
- constructor(private translate: TranslateService, public route: ActivatedRoute, private router: Router, private systemUsersService: SystemUsersService
- , private maskService: MaskService, private http: Http, private modalService: NgbModal, ) {
- const inputs = document.querySelectorAll('.js-photo_submit-input');
- for (var i = 0; i < inputs.length; i++) {
- inputs[i].addEventListener('change', this.uploadImage);
- }
- /*
- * -> variável daysOfTheWeek : valores que são utilizados para exibir de forma dinâmica uma tabela
- * no html, referente ao período de ida e volta do aluno a universidade.
- *
- * -> variável institutions: os valores são usados no html no #selectInstitution para que possa se exibir de forma
- * dinâmica as opções de instituições. Ex: <option *ngFor="let institution of institutions">
- * O mesmo acontece para variáveis:
- * -> bloodTypes referente ao select #selectBlood
- * -> citysInstitution referente ao select #selectCity
- * -> phoneTypes referente ao select #selectPhone
- *
- * -> variáveis timeToGoInstitution e timeToBackInstitution:
- * São instaciadas como arrays na função ngOnInit().Suas posições possuem valores booleanos inicialmente falsos.
- * Os valores são utilizados no htm em uma tabela que possui inputs do tipo checkbox
- *
- * -> Variáveis visualizationPessoais, visualizationEnd, visualizationInsti, visualizationDoc, visualizationSave:
- * Variáveis booleanas utilizadas em *ngIf no html para controlar que parte do formulário é exibida
- *
- * Variáveis classPersonalData, classAddress, classInstitution, classDocuments, classSave:
- * Controlam o status dos passos da lista: passo atual, passo completo ou passo com erro.
- */
- }
- ngOnInit() {
- /* ############ Instanciando Arrays ################# */
- this.daysOfTheWeek = [{ index: 0, name: "Segunda-Feira" },
- { index: 1, name: "Terça-Feira" },
- { index: 2, name: "Quarta-Feira" },
- { index: 3, name: "Quinta-Feira" },
- { index: 4, name: "Sexta-Feira" },
- { index: 5, name: "Sábado" }];
- this.timeToGoInstitution = new Array(6);
- this.timeToBackInstitution = new Array(6);
- for (var i = 0; i < 6; i++) {
- this.timeToGoInstitution[i] = new Array(4);
- this.timeToBackInstitution[i] = new Array(4);
- for (var j = 0; j < 4; j++) {
- this.timeToGoInstitution[i][j] = false;
- this.timeToBackInstitution[i][j] = false;
- }
- }
- /* ############ ################################ ################# */
- // Instacionando o formulário que fará o controle dos valores passados aos input
- this.formNewUser = new FormGroup({
- personalData: new FormGroup({
- student: new FormControl(true),
- teacher: new FormControl(false),
- name: new FormControl(null, [Validators.required, Validators.minLength(5), Validators.maxLength(150), Validators.pattern(/^[a-z\u00C0-\u00ff A-Z]+$/)]),
- email: new FormControl(null, [Validators.required, Validators.minLength(5), Validators.maxLength(65), Validators.pattern(/\S+@\S+\.\S+/)], ),
- cpf: new FormControl(null, [Validators.required, Validators.minLength(11), Validators.maxLength(11), Validators.pattern(/^[0-9]{11}$/)]),
- rg: new FormGroup({
- number: new FormControl(null, [Validators.required, Validators.minLength(2), Validators.maxLength(15)]),
- date: new FormControl(null, Validators.required),
- state: new FormControl(null, [Validators.required, Validators.minLength(2), Validators.maxLength(2), Validators.pattern(/\b[A-Za-z][A-Za-z]/)]),
- }),
- bloodType: new FormControl(null, Validators.required),
- motherSname: new FormControl(null, [Validators.required, Validators.minLength(5), Validators.maxLength(150), Validators.pattern(/^[a-z\u00C0-\u00ff A-Z]+$/)]),
- phone: new FormGroup({
- name: new FormControl(null, Validators.required),
- numberPhone: new FormControl(null, Validators.required),
- })
- }),
- address: new FormGroup({
- street: new FormControl(null, Validators.required),
- number: new FormControl(null, [Validators.required, Validators.maxLength(5)]),
- neighborhood: new FormControl(null, [Validators.required, Validators.minLength(2), Validators.maxLength(30), Validators.pattern(/^[a-z\u00C0-\u00ff A-Z]+$/)])
- }),
- institution: new FormGroup({
- name: new FormControl(null, Validators.required),
- city: new FormControl(null, Validators.required),
- course: new FormControl(null, Validators.required),
- startYear: new FormControl(null, Validators.required),
- yearTermination: new FormControl(null, Validators.required),
- }),
- files: new FormGroup({
- rg: new FormControl(null, Validators.required),
- cpf: new FormControl(null, Validators.required),
- comprovanteR: new FormControl(null, Validators.required),
- comprovanteM: new FormControl(null, Validators.required),
- cadM: new FormControl(null, Validators.required),
- foto: new FormControl(null, Validators.required),
- })
- });
- }
- /**
- * @function getMask chamada pelo html para solicitar uma máscara para o service
- * @param typeField tipo do campo que necessita da máscara
- */
- getMask(typeField): string {
- return this.maskService.getMask(typeField);
- }
- /**
- * @function openVisualizationForms Controla qual parte do html está sendo exibida
- * e faz a validação dos passos a partir dos formGroups do formNewUser ( personalData, address ou institution).
- * @param step passo que ativou a ação
- * @param action ação previous ou next corresponde a qual botão foi clicado anterior ou próximo
- * @example var pD = this.formNewUser.get('personalData'); -> recupera o formGroup.
- * Verifica se pD é valido, se válido : classListaPasso = is-complete, se não classListaPasso = has-error.
- * Essa verficação ocorre na transição dos passos, o passo pode ser is-current (atual), mas só será passo atual
- * na primeira vez que o usuário entrar nele, ou seja, se houver uma transição entre esse passo e outro
- * e ele necessitar de validação já se tornará has-error e a única mudança possível a partir dai é que ele
- * se torne is-complete.
- */
- public openVisualizationForms(step, action) {
- if (step == 'personalData' && action == 'next') {
- var pD = this.formNewUser.get('personalData');
- if (pD.valid) {
- this.textPersonalData = "Completo: ";
- this.classPersonalData = "is-complete";
- } else {
- this.textPersonalData = "Erro: ";
- this.classPersonalData = "has-error";
- }
- this.textAddress = "Passo Atual: ";
- this.classAddress = "is-current";
- this.visualizationPessoais = false;
- this.visualizationEnd = true;
- } else if (step == 'address') {
- var pA = this.formNewUser.get('address');
- this.visualizationEnd = false;
- if (pA.valid) {
- this.textAddress = "Completo: ";
- this.classAddress = "is-complete";
- } else {
- this.textAddress = "Erro: ";
- this.classAddress = "has-error";
- }
- if (action == 'previous') {
- this.visualizationPessoais = true;
- this.textPersonalData = "Passo Atual: ";
- this.classPersonalData = "is-current";
- } else if (action == 'next') {
- this.visualizationInsti = true;
- this.textInstitution = "Passo Atual: ";
- this.classInstitution = "is-current";
- }
- } else if (step == 'institution') {
- var pI = this.formNewUser.get('institution');
- this.visualizationInsti = false;
- this.timeBackValid = 0;
- this.timeGoValid = 0;
- /** interação do array do periodo de ida e volta para descobrir se está valido
- * se ele possuir ao menos 1 elemento selecionado por linha no final o contador é igual a 6
- * e o array é valido e será válido somente se o contador for exatamente 6
- * se for mais (mais de uma coluna selecionada por linha)
- * ou menos já estará inválido.
- */
- for (var i = 0; i < 6; i++) {
- for (var j = 0; j < 4; j++) {
- if (this.timeToGoInstitution[i][j]) this.timeGoValid++;
- if (this.timeToBackInstitution[i][j]) this.timeBackValid++;
- }
- }
- if (pI.valid) {
- if ((this.timeGoValid >= 6) && (this.timeBackValid >= 6)) {
- this.textInstitution = "Completo: ";
- this.classInstitution = "is-complete"
- } else {
- this.errorTable = true;
- this.textInstitution = "Erro: ";
- this.classInstitution = "has-error";
- }
- }
- else {
- if ((this.timeGoValid < 6) && (this.timeBackValid < 6)) {
- this.errorTable = true;
- }
- this.textInstitution = "Erro: ";
- this.classInstitution = "has-error";
- }
- if (action == 'previous') {
- this.visualizationEnd = true;
- this.textAddress = "Passo Atual: ";
- this.classAddress = "is-current";
- } else if (action == 'next') {
- this.visualizationDoc = true;
- this.textDocuments = "Passo Atual: ";
- this.classDocuments = "is-current";
- }
- } else if (step == 'documents') {
- this.visualizationDoc = false;
- if (action == 'previous') {
- this.visualizationInsti = true;
- this.textInstitution = "Passo Atual: ";
- this.classInstitution = "is-current";
- }
- }
- }
- /**
- * @function setValueBloodType utilizada para setar no formControl de tipo sanguíneo, o valor que o usuário informou
- * @param blood contém o valor do input de tipo sanguíneo
- * @description Ela existe, pois da maneira que foi implementado o controle dos valores com um formControl(formNewUser)
- * não é possível setar de maneira automática o valor do formControl correspondente a tipo sanguíneo, nome da instituição..
- * com o valor que é atribuido no select no html, então é preciso passar o valor por parâmetro e setar no .ts
- * @example O controle corresponde é recuperado.
- * var form = this.formNewUser.get('personalData').get('bloodType');
- *
- * O valor do select é setado no valor do controle.
- * form.value = blood;
- *
- * form.markAsTouched() -> essa linha existe para marcar que o controle foi "tocado", ou seja que o usuário setou um valor nele
- * para que o Validators.required seja válido
- *
- * form.updateValueAndValidity(); -> lança um evento para alteração de valores ou validação, pois o formNewUser
- * não consegue fazer esse update de forma automática.
- */
- public setValueBloodType(blood) {
- // todos tipos sao validos, pq "NÃO SEI INFORMAR" também é um tipo valido.
- var form = this.formNewUser.get('personalData').get('bloodType');
- if (blood != 'Não sei informar') {
- form.value = blood;
- } else {
- form.value = null;
- }
- form.markAsTouched();
- form.updateValueAndValidity();
- }
- /**
- * @function setValueInstitution utilizada para setar no formControl do nome da instituição, o valor que o usuário informou
- * @param inst contém o valor do input do nome da instituição
- */
- public setValueInstitution(inst) {
- var form = this.formNewUser.get('institution').get('name');
- if (inst != 'Escolha uma instituição') {
- form.value = inst;
- } else {
- form.value = null;
- }
- form.markAsTouched();
- form.updateValueAndValidity();
- }
- /**
- * @function setValueCity utilizada para setar no formControl de cidade da instituição, o valor que o usuário informou
- * @param city contém o valor do input do nome da cidade
- */
- public setValueCity(city) {
- var form = this.formNewUser.get('institution').get('city')
- if (city != 'Escolha uma cidade') {
- form.value = city;
- }
- else {
- form.value = null;
- }
- form.markAsTouched();
- form.updateValueAndValidity();
- }
- /**
- * @function setValuePhoneType utilizada para setar no formControl do tipo de telefone, o valor que o usuário informou
- * @param phone contém o valor do input do tipo de telefone
- */
- public setValuePhoneType(phone) {
- var form = this.formNewUser.get('personalData').get('phone').get('name');
- if (phone != 'Tipo') {
- form.value = phone;
- }
- else {
- form.value = null;
- }
- form.markAsTouched();
- form.updateValueAndValidity();
- }
- /**
- * @function setValuetimeToGoInstitution utiliza para mudar o valor booleano do array correspondente ao período de ida a universidade
- * @param i linha correspondente ao dia da semana que precisa ter o valor trocado
- * @param j coluna correspondente ao período que precisa ter o valor trocado
- */
- public setValuetimeToGoInstitution(i, j) {
- this.timeToGoInstitution[i][j] = !this.timeToGoInstitution[i][j];
- }
- /**
- * @function setValuetimeToBackInstitution utiliza para mudar o valor booleano do array correspondente ao período de retorno da universidade
- * @param i linha correspondente ao dia da semana que precisa ter o valor trocado
- * @param j coluna correspondente ao período que precisa ter o valor trocado
- */
- public setValuetimeToBackInstitution(i, j) {
- this.timeToBackInstitution[i][j] = !this.timeToBackInstitution[i][j];
- }
- /**
- * @function onFileChange utilizada para recuperar o arquivo que usuário fez upload no input e atribuí-lo ao FileControl do formNewUser,
- * pois é preciso guardar esses arquivo no controle para mandar para o backend.
- * @param event evento contém os dados do momento que a função foi disparada
- */
- public onFileChange(event) {
- /*
- * a função de fileChange é chamada cada vez que há uma mudança de valores em algum input do file
- * que estão no html. Como em cada input estamos fazendo o upload de apenas 1 arquivo
- * no array de arquivos que o evento retorna sempre haverá apenas 1 arquivo
- * por isso utilizamos event.target.files[0], se houvesse mais de um arquivo por input seria preciso tratar.
- */
- //nome do campo que lançou o evento
- var id = event.target.id;
- // Controle do formNewUser para arquivos
- var fileControl = this.formNewUser.controls.files;
- var file = event.target.files[0];
- var extensao = file.name.split('.').pop();
- var date = new Date;
- /* A atribuição de valor é feita de forma específica
- * se o arquivo que lançou o evento veio do input de rg,
- * o fileControl do rg que receberá seu valor. Se veio do input de cpf, o fileControl do cpf que receberá seu valor.
- */
- if (id == 'inputFileRg') {
- fileControl.get('rg').value = new File([file], 'rg' + '.' + extensao, { type: file.type });
- /*
- * new File([file], 'rg' + '.' + extensao, { type: file.type });
- * Utilizamos esse tipo de construtor apenas para que fosse possível renomear o arquivo
- * poderia ser feita a atribuição : fileControl.get('rg').value = file
- * só que ele conteria todas as informações originais dos arquivo.
- */
- } if (id == 'inputFileCpf') {
- fileControl.get('cpf').value = new File([file], 'cpf' + '.' + extensao, { type: file.type });
- } if (id == 'inputFileComprovanteR') {
- fileControl.get('comprovanteR').value = new File([file], 'comprovante_residencia' + '.' + extensao, { type: file.type });
- } if (id == 'inputFileComprovanteM') {
- /* Nesse if é feito um tratamento de data, pois ele é referente ao comprovante de matrícula
- * então é preciso saber se ele é do primeiro ou segundo semestre.
- */
- if (date.getMonth() < 6) {
- fileControl.get('comprovanteM').value = new File([file], date.getFullYear() + '_1' + '_' + 'comprovante_matricula' + '.' + extensao, { type: file.type });
- } else {
- fileControl.get('comprovanteM').value = new File([file], date.getFullYear() + '_2' + '_' + 'comprovante_matricula' + '.' + extensao, { type: file.type });
- }
- } if (id == 'inputFileCM') {
- fileControl.get('cadM').value = new File([file], 'cadastro_municipal' + '.' + extensao, { type: file.type });
- } if (id == 'inputFileFoto') {
- fileControl.get('foto').value = new File([file], '3x4' + '.' + extensao, { type: file.type });
- }
- fileControl.updateValueAndValidity();
- }
- /**
- * @function downloadArquivo utizada para fazer download de um arquivo
- * @param file arquivo a ser baixado
- */
- public downloadArquivo(file): void {
- /*Cria um novo objeto URL, cujo tempo de vida está ligado ao document na janela na qual este objeto foi criado.
- O novo objeto URL representa o objeto File ou o objeto Blob passado como argumento.*/
- var url = window.URL.createObjectURL(file);
- var a = document.createElement("a");
- a.setAttribute("href", url);
- //propriedade que precisa ser instaciada para que seja possível fazer o dowload do arquivo
- a.setAttribute("download", file.name);
- a.click();
- }
- /**
- * @function onSubmit utilizada para submeter os dados informados pelo o usuário para cadastro
- */
- public onSubmit() {
- var documents: Array<UsersDocuments> = new Array();
- const phonesControl = this.formNewUser.controls.personalData.controls.phone; // controle dos telefones
- const addressControl = this.formNewUser.controls.address; // controle dos endereços
- var personalDataControl = this.formNewUser.controls.personalData;
- var institutionControl = this.formNewUser.controls.institution;
- var profession;
- // adicionando no array de documentos os valores passados nos inputs
- documents.push({ name: "CPF", value: personalDataControl.get('cpf').value, expeditionDate: null, state: null });
- documents.push({ name: "RG", value: personalDataControl.get('rg').get('number').value, expeditionDate: personalDataControl.get('rg').get('date').value, state: personalDataControl.get('rg').get('state').value });
- // recuperando o valor do input de profissão e setando na variável profession
- // personalDataControl.get('teacher').value retorna um valor verdadeiro (true) ou falso (false)
- if (personalDataControl.get('teacher').value) {
- profession = "PROFESSOR";
- }
- if (personalDataControl.get('student').value) {
- profession = "ESTUDANTE";
- }
- //construindo o objeto com as informações do novo usuário para mandar para o backend
- var newUserU: SystemUserUniversityTransportation = new SystemUserUniversityTransportation(
- personalDataControl.get('name').value,
- personalDataControl.get('email').value,
- '',
- '',
- // personalDataControl.get('login').value,
- //personalDataControl.get('password').value,
- '',
- documents,
- [{ //ADDRESS
- name: 'RESIDENCIAL',
- street: addressControl.get('street').value,
- number: addressControl.get('number').value,
- complement: null,
- neighborhood: addressControl.get('neighborhood').value,
- zip_code: '15385000',
- city: 'Ilha Solteira',
- state: 'SP'
- }],
- [{ //PHONE
- name: phonesControl.get('name').value,
- number_phone: phonesControl.get('numberPhone').value
- }],
- this.formNewUser.active,
- new UniversityTransportation(
- profession,
- personalDataControl.value.bloodType,
- personalDataControl.value.motherSname,
- new Institution(
- institutionControl.get('name').value,
- institutionControl.get('city').value,
- institutionControl.get('course').value,
- institutionControl.get('startYear').value,
- institutionControl.get('yearTermination').value,
- this.timeToGoInstitution,
- this.timeToBackInstitution
- )
- )
- );
- this.systemUsersService.registerUsersAdmTransporte(newUserU, this.token)
- .subscribe((apiResponse: string) => {
- var id: string = apiResponse;
- const fileControl = this.formNewUser.get('files');
- const formData: any = new FormData();
- var teste = this.formNewUser.controls.files.controls;
- formData.append('userId', id);
- for (const control in this.formNewUser.get('files').controls) {
- var file = fileControl.get(control).value;
- if (file != null) {
- formData.append("uploads[]", file, file['name']);
- }
- }
- this.systemUsersService.filesUpload(formData, this.token).
- subscribe((apiResponse: Object) => {
- alert('Usuário Cadastrado com sucesso!');
- this.router.navigateByUrl('/university-transportation/UniversityTransportationHome'); //ROTEAMENTO
- }, (error: any) => {
- alert('erro na submissão do cadastro de usuário')
- if (error._body === '{"errors":["Usuário já cadastrado."]}') {
- alert('Já cadastrado')
- }
- });
- });
- }
- public openRg(contentRg): void {
- this.modalService.open(contentRg).result.then((result) => {
- this.closeView = `Closed with: ${result}`;
- }, (reason) => {
- this.closeView = `Dismissed ${this.getDismissReason(reason)}`;
- });
- }
- public openCpf(contentCpf): void {
- this.modalService.open(contentCpf).result.then((result) => {
- this.closeView = `Closed with: ${result}`;
- }, (reason) => {
- this.closeView = `Dismissed ${this.getDismissReason(reason)}`;
- });
- }
- public openRes(contentRes): void {
- this.modalService.open(contentRes).result.then((result) => {
- this.closeView = `Closed with: ${result}`;
- }, (reason) => {
- this.closeView = `Dismissed ${this.getDismissReason(reason)}`;
- });
- }
- public openMat(contentMat): void {
- this.modalService.open(contentMat).result.then((result) => {
- this.closeView = `Closed with: ${result}`;
- }, (reason) => {
- this.closeView = `Dismissed ${this.getDismissReason(reason)}`;
- });
- }
- public openCad(contentCad): void {
- this.modalService.open(contentCad).result.then((result) => {
- this.closeView = `Closed with: ${result}`;
- }, (reason) => {
- this.closeView = `Dismissed ${this.getDismissReason(reason)}`;
- });
- }
- public openPhoto(contentPhoto): void {
- this.modalService.open(contentPhoto).result.then((result) => {
- this.closeView = `Closed with: ${result}`;
- }, (reason) => {
- this.closeView = `Dismissed ${this.getDismissReason(reason)}`;
- });
- }
- private getDismissReason(reason: any): string {
- if (reason === ModalDismissReasons.ESC) {
- return 'by pressing ESC';
- } else if (reason === ModalDismissReasons.BACKDROP_CLICK) {
- return 'by clicking on a backdrop';
- } else {
- return `with: ${reason}`;
- }
- }
- showPreviewRg(event) {
- var reader = new FileReader();
- reader.onload = (event: any) => {
- this.localUrlRg = event.target.result;
- }
- reader.readAsDataURL(event);
- }
- showPreviewCpf(event) {
- var reader = new FileReader();
- reader.onload = (event: any) => {
- this.localUrlCpf = event.target.result;
- }
- reader.readAsDataURL(event);
- }
- showPreviewRes(event) {
- var reader = new FileReader();
- reader.onload = (event: any) => {
- this.localUrlRes = event.target.result;
- }
- reader.readAsDataURL(event);
- }
- showPreviewMat(event) {
- var reader = new FileReader();
- reader.onload = (event: any) => {
- this.localUrlMat = event.target.result;
- }
- reader.readAsDataURL(event);
- }
- showPreviewCad(event) {
- var reader = new FileReader();
- reader.onload = (event: any) => {
- this.localUrlCad = event.target.result;
- }
- reader.readAsDataURL(event);
- }
- showPreviewPhoto(event) {
- var reader = new FileReader();
- reader.onload = (event: any) => {
- this.localUrlPhoto = event.target.result;
- }
- reader.readAsDataURL(event);
- }
- /**
- * @function changeLang utilizada para traduzir a página
- * @param language linguagem para qual a página deve ser traduzida
- * @description palavras usadas na tradução : assets/i18n
- */
- changeLang(language: string) {
- this.translate.use(language);
- }
- uploadImage(e) {
- const fileInput = e.target;
- const uploadBtn = e.target.parentNode;
- const deleteBtn = e.target.parentNode.childNodes[7];
- const reader = new FileReader();
- //console.log(e.target.files[0].type)
- reader.onload = function (e: any) {
- uploadBtn.setAttribute('style', `background-image: url('${e.target.result}');`);
- uploadBtn.classList.add('photo_submit--image');
- fileInput.setAttribute('disabled', 'disabled');
- };
- reader.readAsDataURL(e.target.files[0]);
- deleteBtn.addEventListener('click', () => {
- uploadBtn.removeAttribute('style');
- uploadBtn.classList.remove('photo_submit--image');
- setTimeout(() => {
- fileInput.removeAttribute('disabled', 'disabled');
- }, 200);
- });
- }
- }
- /*
- public erroRg: boolean = false;
- public erroCpf: boolean = false;
- public erroFoto: boolean = false;
- public erroCpr: boolean = false;
- public erroCpm: boolean = false;
- public erroCdm: boolean = false;
- verificaDocs() {
- const fileControl = this.formNewUser.get('files');
- if (fileControl.get('rg').value == null) {
- this.erroRg = true;
- } else {
- this.erroRg = false;
- }
- if (fileControl.get('cpf').value == null) {
- this.erroCpf = true;
- } else {
- this.erroCpf = false;
- }
- if (fileControl.get('foto').value == null) {
- this.erroFoto = true;
- } else {
- this.erroFoto = false;
- }
- if (fileControl.get('comprovanteR').value == null) {
- this.erroCpr = true;
- } else {
- this.erroCpr = false;
- }
- if (fileControl.get('comprovanteM').value == null) {
- this.erroCpm = true;
- } else {
- this.erroCpm = false;
- }
- if (fileControl.get('cadM').value == null) {
- this.erroCdm = true;
- } else {
- this.erroCdm = false;
- }
- }
- */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement