3
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 is created a button to delete 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 in Angular 2? Varri Google, I could only find something to add with Elmentref, but not to delete.
The Angular framework, in general, is strongly related to the idea of state. This way, I can tell you that you don’t have to indirectly manipulate the DOM to accomplish what you want (but you can manipulate the DOM to do this, but you lose some interesting Angular 2 features). I advise you to read this topic in the Angular 2 documentation (https://scotch.io/tutorials/how-to-build-nested-model-driven-forms-in-angular-2). In this link you will find what you want. Good learning.
– Victor Schinaider
That really was it. Thank you
– Fernando Herique Rubim Pioli
You can make the existing HTML button and use the *ngIf="" directive to show it or not. In the DOM itself it will only be created if *ngIf is true.
– Lucas Brogni