How to apply javascript events to Angular?

Asked

Viewed 226 times

0

I’m having a huge difficulty applying Javascript in my Angular project, I hit the setup to connect javascript in the project, but come on...

This is the Javascript file;

var Brewer = Brewer || {};

Brewer.MascaraCpfCnpj = (function() {

    function MascaraCpfCnpj() {
        this.radioTipoPessoa = $('.js-radio-tipo-pessoa');

    }

    MascaraCpfCnpj.prototype.iniciar = function() {
        this.radioTipoPessoa.on('change', onTipoPessoaAlterado.bind(this));
    }

    function onTipoPessoaAlterado(evento) {
        console.log('evento', evento);
    }

    return MascaraCpfCnpj;

}());

$(function() {
    var mascaraCpfCnpj = new Brewer.MascaraCpfCnpj();
    mascaraCpfCnpj.iniciar();
});

And this is the excerpt from the Javascript file that was applied to the event;

  <div class="ui-g-12 ui-lg-3 ui-md-6 ui-fluid">
        <label for="id_FISICA">Tipo de Pessoa Física</label>
            <div class="radio">
                <p-radioButton class="js-radio-tipo-pessoa" name="group1" value="Física" id="id_FISICA" [(ngModel)]="tipo" inputId="tipo"></p-radioButton>
            </div>
      </div>
      <div class="ui-g-12 ui-lg-3 ui-md-6 ui-fluid">
        <label for="id_JURIDICA">Tipo de Pessoa Júridica</label>
            <div class="radio">
              <p-radioButton class="js-radio-tipo-pessoa" name="group1" value="Juridica" id="id_JURIDICA" [(ngModel)]="tipo" inputId="tipo"></p-radioButton>
            </div>
      </div>

Something was supposed to appear in the browser console when clicking on the radiobutton, but it appears absolutely nothing, nothing at all.

I’m open to suggestions

  • Why you are using jQuery and native Javascript events ?

  • why does it work.

1 answer

2


I don’t see much point in using jQuery to do this being that the Angular itself supports it natively.

Using the native events, you can build a form and subscribe to its value in the following way:

app.componentts.

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
  name = 'Angular 5';
  myForm: FormGroup;
  constructor(fb: FormBuilder) {
    this.myForm = fb.group({
      identifier: ['']
    })
  }

  ngOnInit(){
    this.myForm.controls.identifier.valueChanges.subscribe(
      value => {
        console.log(value);
      }
    )
  }
}

app.component.html

<form [formGroup]="myForm">
  <input formControlName="identifier"> 
</form>

Browser other questions tagged

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