If I want to remove/add element on DOM
I just use ng-if
and the code under it does not compile into to DOM, can I do the same using pure js? I don't want the HTML code inside my js code.
Hiding it using CSS:
<div id = "infoPage" style="display: none;">
Will still insert the element to the DOM.
EDIT
The condition for showing or not is based on a flag like:
var show = false; //or true
You can try something like this:
Object.defineProperty
. This way you can have your own setter and you can observe changes over it. 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)
<div class='content'> <div id="infoPage"> test </div> </div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.