Handle non-angular DOM 2

2

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. (follow 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--;
});

Doubt is, how to do this in angular 2? I tried to find something to add with ElmentRef, but not to delete it.

    
asked by anonymous 19.12.2016 / 19:51

1 answer

0

According to the style guide of angular2, you should avoid using ElementRef because it can cause vulnerability in your application because this way it gives 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 securely.  You can make your code as in the example below.

Within yourComponent.component.ts you place this code:

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

        }

And in HTML you can use this way:

<button  (click)='clicou(mostrar)'> <span>ativa/desativa</span></button>
<button *ngIf="mostrar">
<span>Ativado</span>  
</button>
<button *ngIf="!mostrar">
<span>Desativado</span>
</button>
    
31.10.2017 / 14:11