在Angular 2中操纵Dom [英] Manipulating Dom in Angular 2
问题描述
我正在创建一个角度为2的Web。我有一个Jquery代码,在单击自定义按钮时添加2个输入和1个删除按钮,因此,当用户单击删除按钮时,它会删除输入(操作DOM)。
I'm creating a web in angular 2. I have a Jquery code to add 2 inputs and 1 delete button when a custom button is clicked,so, when the user clicks on delete button, it remove the inputs ( manipulating the DOM ).
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--;
});
我如何在Angular 2中执行此操作?
我读到了关于elementRef和Renderer的内容,但我很困惑。
How can I do this in Angular 2? I read about elementRef and Renderer, but I'm so confusing.
推荐答案
在Angular中你没有注入从JavaScript进入您的页面的HTML。 (你可以,但这不是一个好习惯)
In Angular you don't inject HTML into your page from JavaScript. (you can, but it's not a good practice)
所有HTML都应该在你的模板中,用* ngIf标签包装,以便在需要时添加和删除元素。 / p>
All the HTML should be in your template, wrapped with *ngIf tags to add and remove the elements when needed.
<div *ngIf="isShowing"> your HTML here </div>
然后你可以绑定到一个按钮的(click)事件来切换点击时的布尔'isShowing':
Then you can bind to a button's (click) event to toggle the boolean 'isShowing' when clicked:
<input (click)="isShowing=false">
所以最终表格应如下所示:
So the final form should look something like this:
<div>
<h2>form</h2>
<form>
<div *ngIf="showForm">
<input type="text">
<input type="text">
<button type="button" (click)="showForm=false">hide form</button>
</div>
<button *ngIf="!showForm" type="button" (click)="showForm=true">show form</button>
</form>
</div>
这篇关于在Angular 2中操纵Dom的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!