如果我想在DOM
上删除/添加元素,我只使用ng-if
并且其下的代码不会编译到DOM中,我可以使用纯js执行相同的操作吗?我不想在我的js代码中使用HTML代码。
使用CSS隐藏它:
<div id = "infoPage" style="display: none;">
仍会将元素插入DOM。
修改
显示与否的条件基于如下标志:
var show = false; //or true
答案 0 :(得分:3)
您可以尝试这样的事情:
Object.defineProperty
创建属性。这样你就可以拥有自己的setter,你可以观察它的变化。
var CustomNGIf = function(element, callback, propertyName) {
var _value = null;
// Create copies of elements do that you can store/use it in future
this.parent = element.parentNode;
this.element = element;
this.clone = null;
// Create a property that is supposed to be watched
Object.defineProperty(this, propertyName, {
get: function() {
return _value;
},
set: function(value) {
// If same value is passed, do nothing.
if (_value === value) return;
_value = !!value;
this.handleChange(_value);
}
});
this.handleChange = function(value) {
this.clone = this.element.cloneNode(true);
if (_value) {
var index = Array.from(this.parent.children).indexOf(this.element);
// Check if element is already existing or not.
// This can happen if some code breaks before deleting node.
if (index >= 0) return;
this.element = this.clone.cloneNode(true);
this.parent.appendChild(this.element);
} else {
this.element.remove();
}
// For any special handling
callback && callback();
}
}
var div = document.getElementById('infoPage');
const propName = 'value';
var obj = new CustomNGIf(div, function() {
console.log("change")
}, propName);
var count = 0;
var interval = setInterval(function() {
obj[propName] = count++ % 2;
if (count >= 10) {
window.clearInterval(interval);
}
}, 2000)
&#13;
<div class='content'>
<div id="infoPage"> test </div>
</div>
&#13;