17.10.2018 Views

Angular

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 25: Detecting resize events<br />

Section 25.1: A component listening in on the window resize<br />

event<br />

Suppose we have a component which will hide at a certain window width.<br />

import { Component } from '@angular/core';<br />

@Component({<br />

...<br />

template: `<br />

<br />

Now you see me...<br />

now you don't!<br />

<br />

`<br />

...<br />

})<br />

export class MyComponent {<br />

visible: boolean = false;<br />

breakpoint: number = 768;<br />

constructor() {<br />

}<br />

}<br />

onResize(event) {<br />

const w = event.target.innerWidth;<br />

if (w >= this.breakpoint) {<br />

this.visible = true;<br />

} else {<br />

// whenever the window is less than 768, hide this component.<br />

this.visible = false;<br />

}<br />

}<br />

A p tag in our template will hide whenever visible is false. visible will change value whenever the onResize event<br />

handler is invoked. Its call occurs every time window:resize fires an event.<br />

GoalKicker.com – <strong>Angular</strong> 2 Notes for Professionals 111

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!