jquery – Manipulate DOM at angle 2

Question:

I'm passing a web system that has Jquery to Angular 2. I have a button that when clicked it adds two inputs and together with them a button is created to exclude these inputs. (follows the code in Jquery)…

//Adiciona campos extra nos sócios
var campos_max = 10;   //max de 10 campos
var x = 1; // campos iniciais

$('#add_field').click (function(e) {
    e.preventDefault();     //prevenir novos clicks
        if (x < campos_max) {
                $('#listas').append('<div>\
                        <div class="form-group">\
 <label class="col-sm-2 control-label">Nome sócio:</label>\
 <div class="input-group">\
     <span class="input-group-addon">*</span>\
        <input class="form-control socio" name="nome[]" type="text" placeholder="Nome sócio..." required>\
 </div>\
   </div>\
   <div class="form-group">\
 <label class="col-sm-2 control-label">Participação (%):</label>\
 <div class="input-group">\
     <span class="input-group-addon">*</span>\
        <input class="form-control socio part" name="participacao[]" type="text" placeholder="Participação..." required number="true">\
 </div>\
   </div>\
    <input href="#" type="button" id="add_field" value="Remover campo" class="remover_campo btn btn-warning">\
                        </div>');
                x++;
        }
});

// Remover o div anterior
$('#listas').on("click",".remover_campo",function(e) {
        e.preventDefault();
        $(this).parent('div').remove();
        x--;
});

The question is, how to do this on angular 2? I scanned google, I could only find something to add with ElmentRef, but not to delete.

Answer:

According to angular2's Style guide, you should avoid using ElementRef because it can cause vulnerability in your application because this way it makes direct access to the DOM, so you can suffer XXS attacks. If you need to change the DOM you can use the renderer , it is part of the angular/core package and has several methods that change the DOM safely. You can make your code as in the example below.

Inside yourComponent.component.ts you put this code:

private mostrar:boolean=false;
    clicou(mostrar) {
      console.log(mostrar)
       this.mostrar= !this.mostrar;

        }

And in HTML you can use it like this:

<button  (click)='clicou(mostrar)'> <span>ativa/desativa</span></button>
<button *ngIf="mostrar">
<span>Ativado</span>  
</button>
<button *ngIf="!mostrar">
<span>Desativado</span>
</button>
Scroll to Top
AllEscort