Detecting real time window size changes in Angular 4
To get it on init
public innerWidth: any;
ngOnInit() {
this.innerWidth = window.innerWidth;
}
If you wanna keep it updated on resize:
@HostListener('window:resize', ['$event'])
onResize(event) {
this.innerWidth = window.innerWidth;
}
Angular window resize event
<div (window:resize)="onResize($event)"
onResize(event) {
event.target.innerWidth;
}
or using the HostListener decorator:
@HostListener('window:resize', ['$event'])
onResize(event) {
event.target.innerWidth;
}
Supported global targets are window
, document
, and body
.
Until https://github.com/angular/angular/issues/13248 is implemented in Angular it is better for performance to subscribe to DOM events imperatively and use RXJS to reduce the amount of events as shown in some of the other answers.
How to get height and width of device display in angular2 using typescript?
I found the solution. The answer is very simple. write the below code in your constructor.
import { Component, OnInit, OnDestroy, Input } from "@angular/core";
// Import this, and write at the top of your .ts file
import { HostListener } from "@angular/core";
@Component({
selector: "app-login",
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit, OnDestroy {
// Declare height and width variables
scrHeight:any;
scrWidth:any;
@HostListener('window:resize', ['$event'])
getScreenSize(event?) {
this.scrHeight = window.innerHeight;
this.scrWidth = window.innerWidth;
console.log(this.scrHeight, this.scrWidth);
}
// Constructor
constructor() {
this.getScreenSize();
}
}
====== Working Code (Another) ======
export class Dashboard {
mobHeight: any;
mobWidth: any;
constructor(private router:Router, private http: Http){
this.mobHeight = (window.screen.height) + "px";
this.mobWidth = (window.screen.width) + "px";
console.log(this.mobHeight);
console.log(this.mobWidth)
}
}
Update DOM When Screen Changes Size (And After Page Loads) In Angular
Why not use Media Query-based CSS rules?
Some simple media query rules in your stylesheet should work much more simply, and not require browser script engine time or angular ngOnInit()
cycles. Try this:
/* CSS */
ngb-carousel {
display: none;
}
.homepage-img-card {
display: block;
}
@media screen and (max-width: 767px) {
ngb-carousel {
display: block;
}
.homepage-img-card {
display: none;
}
}
You can dispense then with all of the typescript. These CSS rules will be enough and will apply immediately and seamlessly whenever the viewport is resized.
Angular get window size onload
ngOnInit() {
this.isSmallScreen = (window.innerWidth) > 600;
}
Element height and width change detection in Angular 2
Edit: Modern answer
Modern browsers support the ResizeObserver API. The API has been out for a number of years and is now widely supported. Unfortunately, Edge only supports it now that it's on Chromium. If that matters to you, look at the old answer or use a polyfill.
If you're interested, here goes. You want to create a ResizeObserver
object and call observe
on it. In this example, the blue block keeps resizing as we cycle the text and padding. The current size of the element is added to the unordered list.
const btn = document.getElementById('btn');
const container = document.getElementById('container');
const output = document.getElementById('output');
btn.onclick = () => {
if (index > 2) {
if (container.className === '') {
container.className = 'high';
} else {
container.className = '';
}
index = 0;
}
container.innerText = values[index++];
}
let index = 0;
const values = [
'Short',
'Longer text',
'Very much longer text of the kind that will fill a large container',
];
function createEntry(text) {
const li = document.createElement('li');
li.innerText = text;
output.appendChild(li);
}
let obs = new ResizeObserver(entries => {
console.log(entries)
for (let entry of entries) {
const cr = entry.contentRect;
createEntry(`Element size: ${cr.width}px x ${cr.height}px`)
}
});
obs.observe(container);
#container {
display: inline-block;
background: lightblue;
}
.high {
padding: 1rem;
}
<div>
<button id="btn">Cycle</button>
</div>
<div id="container">Test This</div>
<ul id="output">
</ul>
How to perform change detection on div resizing
You can add a directive to the div
and implement lifecycle hook ngDoCheck()
to perform your own change detection logic. You'll need to inject ElementRef
:
constructor(private _elRef:ElementRef) {}
ngDoCheck() {
// use ElementRef to examine the div property of interest
If the div
is inside a component template, add a local template variable
<div #myDiv ...>
Then use @ViewChild()
to get a reference to the div
and implement lifecycle hook ngDoCheck()
or ngAfterViewChecked()
to perform your own change detection logic.
@ViewChild('myDiv') theDiv:ElementRef;
ngAfterViewChecked() {
// use this.theDiv to examine the div property of interest
Note that ngDoCheck() and ngAfterViewChecked() will be called every time change detection runs. See also the dev guide Lifecycle Hooks.
Related Topics
How to Use an <H2> Tag </H2> Inside a <P></P> in The Middle of a Text
Twitter Bootstrap: Center Pills
Draw Double Curved Item with Beveled Edges
How to Change Svg Color When It Is an Encoded CSS Background Image
Svg Lineargradient Hidden If Svg Is Hidden in Seperate Class
Method to Convert HTML5 Canvas to Svg
How to Horizontal & Vertical Center a Div
Conditional Rendering of Non-Jsf Components (Plain Vanilla HTML and Template Text)
HTML Contenteditable with Non-Editable Islands
Is Form Enctype "Application/JSON" Available
What's The Point of Having Hidden Input in HTML? What Are Common Uses for This
Removing Unwanted Table Cell Borders with CSS
How to Make Image Caption Width to Match Image Width
CSS - Make Div's Inherit a Height