I'm trying to access the DOM elements of one of my pages with the following:
ionViewDidEnter() {
this.platform.ready().then(() => {
let elm = <HTMLElement>document.querySelector("ion-navbar.toolbar.toolbar-ios.statusbar-padding");
console.log(elm.style);
})
}
However, it appears this element has no style - I have tried various combinations to access it but no luck.
Specifically, I'm looking for the height of the ion-navbar. Is this possible?
You can get the actual height of an element with element.offsetHeight.
As for the style property, it will give you only the attributes defined in the element's inline style attribute (e.g. <div style="height: 20px;">...</div>), not the ones applied by the CSS using selector rules. See this MDN article for more details.
This is my workaround for that.
let tabs = document.querySelectorAll('.show-tabbar');
if (tabs !== null) {
Object.keys(tabs).map((key) => {
tabs[key].style.transform = 'translateY(56px)';
});
}
I always have found it terribly useful to simply use
ionic serve
inspect the element in chrome and easily see the style for the given device.
To access the DOM element in angular I have used the #id route. The following snippet was used to verify the appropriate class was applied by ionic.
html- home.html
<ion-spinner #testspinner name="crescent" paused="{{isPaused}}"></ion-spinner>
ts- home.ts
import {Component} from '#angular/core';
import {ViewChild} from '#angular/core';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
isPaused: boolean;
#ViewChild('testspinner') testspinner;
constructor() {
this.isPaused = false; // set to true will cause to never have animation state running.
}
containsPausedClass(list: string[]) {
return (list.indexOf('spinner-paused') != -1);
}
ngAfterViewInit() {
// if the spinner is allows to load without 'spinner-paused' then safari will work.
setTimeout(() => {
this.isPaused = true;
}, 0);
console.log('test spinner is paused ',
this.containsPausedClass(this.testspinner._elementRef.nativeElement.classList.value));
}
togglePause() {
this.isPaused = !this.isPaused;
setTimeout(() => {
console.log('test spinner is paused ',
this.containsPausedClass(this.testspinner._elementRef.nativeElement.classList.value));
}, 100);
}
}
Related
I have a rich text element in Contentful that has an embedded entry within it. I am attempting to have that embedded entry render inside a custom Angular component. However, when I pass in options to the Contentful documentToHtmlString function, it displays the tag, but does not render anything or even trigger the console.log() function I have inside the custom component typescript file.
TYPESCRIPT for the rendering
convertToHTML(document:any[]) {
const options = {
renderNode: {
[BLOCKS.EMBEDDED_ENTRY]: (node:any, next:any) => `<embed-element [node]="${node}" [content]="${next(node.content)}"></embed-element>`
}
}
let unsafe = documentToHtmlString(document, options);
return this.sanitizer.bypassSecurityTrustHtml(unsafe);
}
HTML for the rendering
<span [innerHTML]="convertToHTML(article.fields.content)"></span>
I have loaded the custom element <embed-element></embed-element> in the providers section of the app.module.ts file as well.
import { EmbedElementComponent } from './shared/components/embed-element/embed-element.component';
#NgModule({
declarations: [
...
EmbedElementComponent
],
providers: [
...
EmbedElementComponent
]
})
Then inside typescript file for the custom element, I just simply have a console.log in the onInit function for testing purposes. I am not seeing this occur in the console.
import { Component, OnInit, Input } from '#angular/core';
#Component({
selector: 'embed-element',
templateUrl: './embed-element.component.html',
styleUrls: ['./embed-element.component.css']
})
export class EmbedElementComponent implements OnInit {
#Input() node: any;
#Input() content: any;
constructor() { }
ngOnInit(): void {
console.log(this.node);
}
}
And in the HTML for the custom element, I removed the <p> tag just in case it was stripping it out as "unsafe" and replaced it with the following:
EMBEDDED ELEMENT WORKS!!!!!
Finally, I see nothing appear on screen for this custom element once everything is rendered. Inside the inspect element however, this is what I get.
<embed-element [node]="[object Object]" [content]=""></embed-element>
How do I manage to make the custom element actually get called in this aspect? And at least receive the console log message I am requesting inside the custom element?
Not sure if you still needed another solution, but I came across ngx-dynamic-hooks https://github.com/MTobisch/ngx-dynamic-hooks - and was able to reuse my custom components within the inner html.
const cmpt_data = {
title: 'This is a test'
};
const headerFooterRichTextOption: Partial<Options> = {
renderNode: {
["embedded-entry-inline"]: (node, next) => `${this.embeddedContentfulEntry(node.nodeType, node.data)}`,
["paragraph"]: (node, next) => `<span>${next(node.content)}</span>`,
}
};
const d = documentToHtmlString(tt.value, headerFooterRichTextOption);
const hSanit = this.sanitizer.bypassSecurityTrustHtml(d);
embeddedContentfulEntry(nodeType: any, data: any) {
return "<custom-component [title]='context.title'></custom-component>";
}
<ngx-dynamic-hooks [content]="hSanit" [context]="cpmt_data"></ngx-dynamic-hooks>
I believe that using a custom component for this type of situation was not working because it was rendering outside of Angulars scope or after initial components initiation.
I resolved this issue by essentially just removing the custom element all together and creating a function that renders the embedded element as I wanted.
// Notice the new function call, renderCustomElement()
convertToHTML(document:any[]) {
const options = {
renderNode: {
[BLOCKS.EMBEDDED_ENTRY]: (node:any, next:any) => this.renderCustomElement(node)
}
}
let unsafe = documentToHtmlString(document, options);
return this.sanitizer.bypassSecurityTrustHtml(unsafe);
}
And finally that function that simply creates some basic html with Bootstrap styling and returns that back to be rendered.
renderCustomElement(node:any) {
let link = `/support-center/article/${node.data.target.fields.category[0].sys.id}/${node.data.target.sys.id}`;
return `<style>.card:hover{box-shadow: 0 0.5rem 1rem rgb(0 0 0 / 15%) !important;}</style><a class="card clickable mb-2 text-decoration-none text-dark" href="${link}" target="_blank"><div class="card-header">Article</div><div class="card-body"><h4 class="fw-light">${node.data.target.fields.title}</h4><p class="fw-light pb-0 mb-0">${node.data.target.fields.preview}</p></div></a>`
}
I'm using a library called ng2-pdf-viewer for some reason the default way to stick to a page isn't working, so what I've done is I've used jQuerys scrollTo() method to scroll to the the .page class in the PDF so if I wanted the page to be scrolled to page 2 it would be page .page:nth-child(2) now I've got this working.. but only after you refresh the page and not when you first land on the page so If I follow a link to my pdf-view page it doesn't scroll but then when I refresh the page it does.. now I'm not sure if using jQuery scrollTo is the best method but its the only way I've been able to kind of get it to work
HTML
<pdf-viewer [src]="pdfSrc"
[render-text]="true"
[autoresize]="true"
[original-size]="false"
style="display: block;" (after-load-complete)="callBackFn($event)">
</pdf-viewer>
COMPONENT.TS
import { Component, OnInit, Output, EventEmitter, AfterViewInit} from '#angular/core';
import { AppConsts } from '#shared/AppConsts';
import { AppComponentBase } from '#shared/common/app-component-base';
import { ActivatedRoute } from '#angular/router';
import { HeaderTitleService } from '#shared/service/headerTitle.service';
declare var jQuery: any;
const $ = jQuery;
#Component({
selector: 'app-pdfview',
templateUrl: './pdfview.component.html',
styleUrls: ['./pdfview.component.less']
})
export class PdfviewComponent implements OnInit {
pdfSrc: string;
pdf: string;
pageNum: number = 2;
botString: string;
pageNumberVar: string;
#Output() notify: EventEmitter<String> = new EventEmitter<String>();
constructor(
private route: ActivatedRoute,
private headerTitleService: HeaderTitleService
) {
this.pdf = route.snapshot.params['pdfId'];
if (this.pdf === '1') {
this.pdfSrc = '../../../assets/pdf/emeds1.pdf';
this.botString = 'Admission Reconciliation loaded on Page 2 - matching the word ‘reconcile’ for you.';
this.pageNumberVar = '2';
} else if (this.pdf === '2') {
this.pdfSrc = '../../../assets/pdf/medrec.pdf';
this.botService.sendMessage('I have loaded the document on page 21 showing "Medication Reconciliation"');
setTimeout(() => {
this.botService.sendMessage('That saved you hours of reading :)');
}, 2000);
setTimeout(() => {
$('html, body').animate({
scrollTop: $('.page:nth-child(29)').offset().top
}, 300);
}, 1000);
}
}
callBackFn(pdf: PDFDocumentProxy) {
this.botService.sendMessage(this.botString);
}
ngAfterViewInit() {
setTimeout(function(){
$('html, body').animate({
scrollTop: $('.page:nth-child(' + this.pageNumberVar + ')').offset().top
}, 300);
}, 1000);
}
}
as you can see above ive tried putting the scrollTo function in ngAfterViewInit but that didnt fix it either
Generally speaking, I believe that it is not a good idea to use jQuery with Angular, since it accesses the browser's DOM directly, bypassing Angular's (emulated) Shadow DOM.
In this case, I think that you can probably do away with your scrollTo fix, and just get the pdf viewer working properly.
I initially had problems with showing the correct page too, but after trying a few things, came up with this working configuration:
<pdf-viewer [src]="pdfSrc"
[(page)]="page"
[show-all]="false"
[rotation]="0"
[zoom]="0.9"
>
</pdf-viewer>
I would start with this, making sure that you get the proper page rendered, and then add your other properties, one at a time, to see what works and what breaks.
I have an angular2 component which manipulates an SVG image based on data it receives from my real time API.
The exact same component is used in two views, the first is a list view, where there are lots of instances of the component.
The second is the detail component where there is only one instance of the component.
However, the component only works in the second view. The component look like:
#Component({
selector: 'app-line-overview',
template: `<object id="img" data="assets/img/big_layout.svg" width="292" height="164" #svg></object>`
})
export class LineOverviewComponent {
stations: string;
#ViewChild('svg') svg: ElementRef;
constructor(public socketService: SocketService) { }
ngOnInit() {
this.socketService.getStations('api/getStations/' + this.line.name).subscribe(stns => {
this.stations = stns.stations;
this.load();
})
}
load() {
let svgDoc = this.svg.nativeElement.contentDocument;
if (this.stations) {
JSON.parse(this.stations).forEach(station => {
station.element = svgDoc.getElementById(station.name);
console.log(station)
station.element.removeAttribute('class');
if (station.status === 'running') {
station.element.setAttribute('fill', 'lime');
}
})
}
}
}
In the list view, station.element is null throwing the error:
inline template:19:24 caused by: Cannot read property 'removeAttribute' of null
Update:
see this [plunk](http://plnkr.co/edit/BNK6rbfBUAleXF6X9ckg?p=preview.
I have an odd requirement and was hoping for some help.
I need to focus on the first found invalid input of a form after clicking a button (not submit). The form is rather large, and so the screen needs to scroll to the first invalid input.
This AngularJS answer would be what I would need, but didn't know if a directive like this would be the way to go in Angular 2:
Set focus on first invalid input in AngularJs form
What would be the Angular 2 way to do this? Thanks for all the help!
This works for me. Not the most elegant solution, but given the constraints in Angular we are all experiencing for this particular task, it does the job.
scrollTo(el: Element): void {
if(el) {
el.scrollIntoView({ behavior: 'smooth' });
}
}
scrollToError(): void {
const firstElementWithError = document.querySelector('.ng-invalid');
this.scrollTo(firstElementWithError);
}
async scrollIfFormHasErrors(form: FormGroup): Promise <any> {
await form.invalid;
this.scrollToError();
}
This works, allowing you to evade manipulating the DOM. It simply goes to the first element with .ng-invalid on the page through the document.querySelector() which returns the first element in the returned list.
To use it:
this.scrollIfFormHasErrors(this.form).then(() => {
// Run any additional functionality if you need to.
});
I also posted this on Angular's Github page: https://github.com/angular/angular/issues/13158#issuecomment-432275834
Unfortunately I can't test this at the moment, so might be a few bugs, but should be mostly there.
Just add it to your form.
import {Directive, Input, HostListener} from '#angular/core';
import {NgForm} from '#angular/forms';
#Directive({ selector: '[scrollToFirstInvalid]' })
export class ScrollToFirstInvalidDirective {
#Input('scrollToFirstInvalid') form: NgForm;
constructor() {
}
#HostListener('submit', ['$event'])
onSubmit(event) {
if(!this.form.valid) {
let target;
for (var i in this.form.controls) {
if(!this.form.controls[i].valid) {
target = this.form.controls[i];
break;
}
}
if(target) {
$('html,body').animate({scrollTop: $(target.nativeElement).offset().top}, 'slow');
}
}
}
}
If you are using AngularMaterial, the MdInputDirective has a focus() method which allow you to directly focus on the input field.
In your component, just get a reference to all the inputs with the #ViewChildren annotation, like this:
#ViewChildren(MdInputDirective) inputs: QueryList<MdInputDirective>;
Then, setting focus on the first invalid input is as simple as this:
this.inputs.find(input => !input._ngControl.valid).focus()
I don't know if this is valid approach or not but this is working great for me.
import { Directive, Input, HostListener, ElementRef } from '#angular/core';
import { NgForm } from '#angular/forms';
import * as $ from 'jquery';
#Directive({ selector: '[accessible-form]' })
export class AccessibleForm {
#Input('form') form: NgForm;
constructor(private el: ElementRef) {
}
#HostListener('submit', ['$event'])
onSubmit(event) {
event.preventDefault();
if (!this.form.valid) {
let target;
target = this.el.nativeElement.querySelector('.ng-invalid')
if (target) {
$('html,body').animate({ scrollTop: $(target).offset().top }, 'slow');
target.focus();
}
}
}
}
In HTML
<form [formGroup]="addUserForm" class="form mt-30" (ngSubmit)="updateUser(addUserForm)" accessible-form [form]="addUserForm"></form>
I have mixed the approach of angularjs accessible form directive in this.
Improvements are welcomed!!!
I've created an Angular directive to solve this problem. You can check it here ngx-scroll-to-first-invalid.
Steps:
1.Install the module:
npm i #ismaestro/ngx-scroll-to-first-invalid --save
2.Import the NgxScrollToFirstInvalidModule:
import {BrowserModule} from '#angular/platform-browser';
import {NgModule} from '#angular/core';
import {NgxScrollToFirstInvalidModule} from '#ismaestro/ngx-scroll-to-first-invalid';
#NgModule({
imports: [
BrowserModule,
NgxScrollToFirstInvalidModule
],
bootstrap: [AppComponent]
})
export class AppModule { }
3.Use the directive inside a form:
<form [formGroup]="testForm" ngxScrollToFirstInvalid>
<input id="test-input1" type="text" formControlName="someText1">
<button (click)="saveForm()"></button>
</form>
Hope it helps!
:)
Plain HTML solution.
If you don't need to be scrolling , just focus on first valid input, I use :
public submitForm() {
if(this.form.valid){
// submit form
} else {
let invalidFields = [].slice.call(document.getElementsByClassName('ng-invalid'));
invalidFields[1].focus();
}
}
This is for template driven form here. We focus on second element of invalidFields cuz first is the whole form which is invalid too.
For Angular Material ,
The below worked for me
#ViewChildren(MatInput) inputs: QueryList <MatInput>;
this.inputs.find(input => !input.ngControl.valid).focus();
I recommend putting this in a service, for me it worked like this:
if (this.form.valid) {
//submit
} else {
let control;
Object.keys(this.form.controls).reverse().forEach( (field) => {
if (this.form.get(field).invalid) {
control = this.form.get(field);
control.markAsDirty();
}
});
if(control) {
let el = $('.ng-invalid:not(form):first');
$('html,body').animate({scrollTop: (el.offset().top - 20)}, 'slow', () => {
el.focus();
});
}
}
#HostListener('submit', ['$event'])
onSubmit(event) {
event.preventDefault();
if (!this.checkoutForm.valid) {
let target;
target = $('input[type=text].ng-invalid').first();
if (target) {
$('html,body').animate({ scrollTop: $(target).offset().top }, 'slow', ()=> {
target.focus();
});
}
}
}
I'm using angular 2. I have a component with an input.
I want to be able to write some code when the input value changes.
The binding is working, and if the data is changed (from outside the component) I can see that there is change in the dom.
#Component({
selector: 'test'
})
#View({
template: `
<div>data.somevalue={{data.somevalue}}</div>`
})
export class MyComponent {
_data: Data;
#Input()
set data(value: Data) {
this.data = value;
}
get data() {
return this._data;
}
constructor() {
}
dataChagedListener(param) {
// listen to changes of _data object and do something...
}
}
You could use the lifecycle hook ngOnChanges:
export class MyComponent {
_data: Data;
#Input()
set data(value: Data) {
this.data = value;
}
get data() {
return this._data;
}
constructor() {
}
ngOnChanges([propName: string]: SimpleChange) {
// listen to changes of _data object and do something...
}
}
This hook is triggered when:
if any bindings have changed
See these links for more details:
https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html
https://angular.io/docs/ts/latest/api/core/OnChanges-interface.html
As mentioned in the comments of Thierry Templier's answer, ngOnChanges lifecycle hook can only detect changes to primitives. I found that by using ngDoCheck instead, you are able to check the state of the object manually to determine if the object's members have changed:
A full Plunker can be found here. But here's the important part:
import { Component, Input } from '#angular/core';
#Component({
selector: 'listener',
template: `
<div style="background-color:#f2f2f2">
<h3>Listener</h3>
<p>{{primitive}}</p>
<p>{{objectOne.foo}}</p>
<p>{{objectTwo.foo.bar}}</p>
<ul>
<li *ngFor="let item of log">{{item}}</li>
</ul>
</div>
`
})
export class ListenerComponent {
#Input() protected primitive;
#Input() protected objectOne;
#Input() protected objectTwo;
protected currentPrimitive;
protected currentObjectOne;
protected currentObjectTwo;
protected log = ['Started'];
ngOnInit() {
this.getCurrentObjectState();
}
getCurrentObjectState() {
this.currentPrimitive = this.primitive;
this.currentObjectOne = _.clone(this.objectOne);
this.currentObjectTwoJSON = JSON.stringify(this.objectTwo);
}
ngOnChanges() {
this.log.push('OnChages Fired.')
}
ngDoCheck() {
this.log.push('DoCheck Fired.');
if (!_.isEqual(this.currentPrimitive, this.primitive)){
this.log.push('A change in Primitive\'s state has occurred:');
this.log.push('Primitive\'s new value:' + this.primitive);
}
if(!_.isEqual(this.currentObjectOne, this.objectOne)){
this.log.push('A change in objectOne\'s state has occurred:');
this.log.push('objectOne.foo\'s new value:' + this.objectOne.foo);
}
if(this.currentObjectTwoJSON != JSON.stringify(this.objectTwo)){
this.log.push('A change in objectTwo\'s state has occurred:');
this.log.push('objectTwo.foo.bar\'s new value:' + this.objectTwo.foo.bar);
}
if(!_.isEqual(this.currentPrimitive, this.primitive) || !_.isEqual(this.currentObjectOne, this.objectOne) || this.currentObjectTwoJSON != JSON.stringify(this.objectTwo)) {
this.getCurrentObjectState();
}
}
It should be noted that the Angular documentation provides this caution about using ngDoCheck:
While the ngDoCheck hook can detect when the hero's name has changed,
it has a frightful cost. This hook is called with enormous frequency —
after every change detection cycle no matter where the change
occurred. It's called over twenty times in this example before the
user can do anything.
Most of these initial checks are triggered by Angular's first
rendering of unrelated data elsewhere on the page. Mere mousing into
another input box triggers a call. Relatively few calls reveal actual
changes to pertinent data. Clearly our implementation must be very
lightweight or the user experience will suffer.