JavaScript .innerHTMLworking only when called manually - innerhtml

I've got a very simple function, of replacing the innerHTML of a element. I've been trying to debug this for hours but simply can't, and it's infuriating.
When called from a button press the JavaScript (as follows) works well, but when called from another function it doesn't work. I am totally lost as to why this might be, and its a fairly core part of my app
// This loaded function in my actual code is a document listener
// checking for when Cordova is loaded which then calls the loaded function
loaded();
function loaded() {
alert("loaded");
changeText();
}
function changeText() {
alert("started");
document.getElementById('boldStuff').innerHTML = 'Fred Flinstone';
}
Button press and HTML to replace
<div id="main">
<input type='button' onclick='changeText()' value='Change Text'/>
<p>Change this text >> <b id='boldStuff'> THIS TEXT</b> </p>
</div>
It is also here in full on JSFiddle

You are already changed the innerHTML by calling the function loaded(); on onLoad.
Put this in an empty file and same as .html and open with browser and try. I have commented the function loaded();. Now it will be changed in onclick.
<div id="main">
<input type='button' onclick='changeText();' value='Change Text'/>
<p>Change this text >> <b id='boldStuff'> THIS TEXT</b> </p>
</div>
<script>
//loaded();
function loaded() {
alert("loaded");
changeText();
}
function changeText() {
alert("started");
document.getElementById('boldStuff').innerHTML = 'Fred Flinstone';
}
</script>

The problem here is, that the element you're trying to manipulate is not yet existing when you are calling the changeText() function.
To ensure that the code is only executed after the page has finished loading (and all elements are in place) you can use the onload handler on the body element like this:
<body onload="loaded();">
Additionally you should know, that it's very bad practice to manipulate values by using the innerHTML property. The correct way is to use DOM Manipulations, maybe this can help you.

You script loads before the element (boldStuff) is loaded,
Test Link - 1 - Put the js in a seperate file
Test Link - 2 - put the js at the very end, before closing the <body>

Related

DebugElement.query does not work with elements added dynamically to the dom in a spec

I have an app that is using ngx-bootstrap to show a tooltip on mouseover. I want to test that the content, which is dynamically added, shows properly. In order to do this I have a test that looks like this:
it(shows the right tooltip', fakeAsync(() => {
fixture.debugElement.query(By.directive(TooltipDirective))
.triggerEventHandler('mouseover', null);
tick();
fixture.detectChanges();
expect(fixture.debugElement.query(By.css('.tooltip-inner')).nativeElement)
.toBe('the tooltip text');
}
This results in an error that indicates that fixture.debugElement.query(By.css('.tooltip-inner')): "Cannot read property 'nativeElement' of null"
If I print out the content of fixture.debugElement.nativeElement I get this:
<div id="root1" ng-version="5.2.9">
<my-component>
<div ng-reflect-tooltip="the tooltip text">
<img src="images/test.png">
</div>
<bs-tooltip-container role="tooltip" class="tooltip in tooltip-right">
<div class="tooltip-arrow arrow"></div>
<div class="tooltip-inner">the tooltip text</div>
</bs-tooltip-container>
<my-component>
</div>
The important take away is that the html exists - it is just not accessible by the DebugElement.query.
My current solution to get the spec passing is to change the expect to:
expect(fixture.debugElement.nativeElement.textContent.trim())
.toBe('the tooltip text');
This works, but it is a hack that will fall to pieces if I run into a similar situation with multiple tooltips (for example). Has anyone been able to handle this in a better way? Am I not setting this spec up correctly?

angular2 bootstrap4 tooltip doesn't render html, while popover does

I'm using angular2 and bootstrap4. Popover correctly renders raw html as bold text asdf
<img src="assets/images/1.jpg"
data-container="body" data-toggle="popover" data-html="true" data-placement="top"
[attr.data-content]="getM()"/>
However, tooltip renders as plain <b>asdf</b> text including tags
<img src="assets/images/2.jpg"
data-container="body" data-toggle="tooltip" data-html="true" data-placement="top"
[attr.title]="getM()"/>
Component method getM:
public getM(): string {
return '<b>asdf</b>';
}
Both tooltip and popover are initialized the same way
$(function () {
$('[data-toggle="tooltip"]').tooltip({container: 'body'});
$('[data-toggle="popover"]').popover({container: 'body'});
})
Could someone explain why is that and how to solve? It seems this is connected with initialization order, but I just don't know where to look further.
Well, the issue was that my element (which tooltip was attached to) was created dynamically.
In exact, I had a 1 sec delayed service. When new data arrived, the <img> element in my component was recreated, but $('[data-toggle="tooltip"]') selector doesn't work with dynamic elements.
Instead, I had to use this selector
$("body").tooltip({selector: '[data-toggle="tooltip"]'});
Now it works as intended.
PS I'm not a front-end developer, so anyone who can explain it in better terms is welcome.

access local variable within *ngIf

I have a primeng (angular 2) dialog with a dropdown. I want to set focus to the dropdown when the dialog shows. The problem appears to be that my div is rendered conditionally.
My code:
<p-dialog (onShow)="fe.applyFocus()">
<div *ngIf="selectedItem">
<button pButton type="button" (click)="fe.applyFocus()" label="Focus"></button>
<p-dropdown #fe id="reason" [options]="reasonSelects" [(ngModel)]="selectedReason" ></p-dropdown>
</div>
</p-dialog>
In this code the button works fine, but the onShow() (outside the *ngIf div) tells me fe is undefined.
How can I access the local variable inside the *ngIf?
Yes, this is a real pain. Unfortunately, due to the way *ngIf works, it completely encapsulates everything inside (including the tag it's on).
This means anything declared on, or inside, the tag with the ngIf will not be "visible" outside of the ngIf.
And you can't even simply put a #ViewChild in the ts, because on first run it might not be present... So there are 2 known solutions to this problem...
a) You can use #ViewChildren. This will give you a QueryList that you can subscribe to, which will fire off every time the tempalte variable changes (ie. the ngIf turns on or off).
(html template)
<div>{{thing.stuff}}</div>
<my-component #thing></my-component>
(ts code)
#ViewChildren('thing') thingQ: QueryList<MyComponent>;
thing: MyComponent;
ngAfterViewInit() {
this.doChanges();
this.thingQ.changes.subscribe(() => { this.doChanges(); });
}
doChanges() {
this.thing = this.thingQ.first;
}
b) You can use #ViewChild with a setter. This will fire the setter every time the ngIf changes.
(html template)
<div>{{thing.stuff}}</div>
<my-component #thing></my-component>
(ts code)
#ViewChild('thing') set SetThing(e: MyComponent) {
this.thing = e;
}
thing: MyComponent;
Both of these examples should give you a "thing" variable you can now use in your template, outside of the ngIf. You may want to give the ts variable a different name to the template (#) variable, in case there are clashes.
You can separate the use of template on NgIf level:
<ng-container *ngIf="selectedItem; else elseTemplate">
<p-dialog (onShow)="fe.applyFocus()">
<div>
<button pButton type="button" (click)="fe.applyFocus()" label="Focus"></button>
<p-dropdown #fe id="reason" [options]="reasonSelects" [(ngModel)]="selectedReason"></p-dropdown>
</div>
</p-dialog>
</ng-container>
<ng-template #elseTemplate>
<p-dialog>
</p-dialog>
</ng-template>

angular-file-upload - how to make drop zone clickable?

Using nv-file-upload (https://github.com/nervgh/angular-file-upload) how can I make the drop zone act also as a clickable element to select files? Adding {{nv-file-select}} does not seem to work.
The answer is that YOU CANT, there is no way to do this inside that plugin but i use a simple solution for this kind of problems. Add a ng-click inside your dragNdrop tag and call your function:
<div nv-file-drop="" uploader="upload" ng-click="launchFilePicker()">
<div class="drop-box" ng-show="upload.isHTML5" uploader="upload" nv-file-over="" over-class="dragover" filter="image/*,application/pdf">
Drag a file here.
</div>
</div>
<div ng-hide="upload.isHTML5"> <input id="fileDialog" type="file" nv-file-select uploader="upload"/><br/></div>
And inside your controller you do this:
$scope.launchFilePicker = function () {
//$('#fileDialog').click(); //not angular way
angular.element('#fileDialog').trigger('click'); //angular way
};
I hope this help.

Upload file to hidden input using protractor and selenium

I've got a hidden file input field like this:
<input type="file" id="fileToUpload-1827" multiple="" onchange="angular.element(this).scope().setFiles(this)" data-upload-id="1827" class="hidden-uploader">
I'd like to be able to upload files to this. The normal way to do this in protractor would be to do:
ptor.findElement(protractor.By.css('.file-upload-form input')).sendKeys('/path/to/file')
But because the input element isn't visible, I get an error.
I tried:
ptor.driver.executeScript("return $('.file-upload-form input')[0].removeClass('hidden-uploader');").then(function () {
ptor.findElement(protractor.By.css('.file-upload-form input')).sendKeys('hello');
})
But got the error
UnknownError: $(...)[0].removeClass is not a function
It seems ridiculous to have to use executeScript to make an element visible so that I can upload a file, is there a better way? If not, how do I unhide the element?
The full html for the input form is:
<form class="file-upload-form ng-scope ng-pristine ng-valid" ng-if="ajaxUploadSupported">
<strong>Drag files here to upload</strong> or
<label for="fileToUpload-1953">
<div class="btn btn-info select-file-btn">
Click to Select
</div>
</label>
<div>
<input type="file" id="fileToUpload-1953" multiple="" onchange="angular.element(this).scope().setFiles(this)" data-upload-id="1953" class="hidden-uploader">
</div>
</form>
The only way I could find to do this in the end was to use javascript to make the input element visible.
So I have a function unhideFileInputs:
var unhideFileInputs = function () {
var makeInputVisible = function () {
$('input[type="file"]').removeClass('hidden-uploader');
};
ptor.driver.executeScript(makeInputVisible);
}
This contains the function 'makeInputVisible' which is executed in the browser when I call ptor.driver.executeScript(makeInputVisible). Because I know my page contains jQuery I can use the jQuery removeClass method to unhide my file input element.
To see more on how to execute javascript in the browser using webdriver, see the answer to this question (although the answer uses executeAsyncScript rather than executeScript).
To add on user2355213s answer for the more current releases of protractor. ptor is obsolote and instead browser should be used. Also, executeScript() expects a string as parameter. So I ended up using
browser.executeScript('$(\'input[type="file"]\').attr("style", "");');
as my visibility setting was directly applied to the element. Of course, you can also use
browser.executeScript('$(\'input[type="file"]\').removeClass("hidden-uploader");');
depending on your HTML/CSS.