Tips for concealing title when window is resized?

I'm working on a webpage that has a title at the top, but I want to hide it on smaller devices and make it responsive when the window is resized. Currently, I only show the title when the window width (w) is greater than 450 pixels. However, I'm struggling to recompute the width on window resize. Is there a better approach to achieve this? I'm using Ionic 5 and Angular.

<ion-toolbar>
  
  <!-- Title and link back to homepage -->
  <ion-button routerLink="/home" fill="clear" *ngIf="w > 450">
    <ion-title>Inventory System</ion-title>
  </ion-button>
  
  <!-- Show back button if not on homepage -->
  <ion-buttons slot="start" *ngIf="!router.url.includes('/home')">
    <ion-back-button defaultHref="home"></ion-back-button>
  </ion-buttons>

  <!-- Display user avatar, username, and menu if logged in -->
  <ion-item slot="end" *ngIf="loggedin">

    <!-- Profile Picture -->
    <ion-avatar slot="start">
      <ion-img src="./assets/icon/defaultUserIcon.svg"></ion-img>
    </ion-avatar> 

    <!-- Username, opens popover menu -->
    <ion-button (click)="openMenu($event)" fill="clear">
      <ion-label>{{username}}</ion-label>
    </ion-button>  
  </ion-item>

  <!-- Show login link if not logged in -->
  <ion-item slot="end" *ngIf="!loggedin"> 
    <ion-button (click)="login()" fill="clear">
      <ion-label>Login</ion-label>
    </ion-button>  
  </ion-item>

</ion-toolbar>

The width (w) is calculated here:

import { PopoverComponent } from './../popover/popover.component';
import { PopoverController } from '@ionic/angular';
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';

@Component({
  selector: 'app-navbar',
  templateUrl: './navbar.component.html',
  styleUrls: ['./navbar.component.scss'],
})
export class NavbarComponent implements OnInit {
  public w = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
  constructor(private popCtrl: PopoverController, public router: Router) { 
   
  }

  ngOnInit() {}


  async openMenu(ev: any){
    const popover = await this.popCtrl.create({
      component: PopoverComponent,
      event: ev,
    });

    return await popover.present();
  }
  
}

Answer №1

For the title, I decided to assign it an id called #tittel and utilized a media query to hide it when the width drops below 450 pixels.

This is how it was implemented in HTML:

 <ion-button routerLink="/home" fill="clear" id="tittel">
   <ion-title>Inventory System</ion-title>
 </ion-button>

And here is the corresponding CSS code:

#tittel{

}
@media only screen and (max-width: 450px) {
    #tittel{
        display: none;
    }
  }

Answer №2

styleObject = {
 display: "inline-block" //Setting initial display style
}

@HostListener('window:resize')
public checkResize(): void {
     this.elementWidth = document.getElementById('element').offsetWidth
     // Add your code here...
if(this.elementWidth<=450){
     this.styleObject= {
     display: "none"
 }
 }
}

HTML

<div id="element" [ngStyle]="styleObject" #resizeDiv ></canvas>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Loop through an array of objects that each contain two sub-objects using ng

I'm looking to organize each data-record in an object that contains two other objects structured like this: data Object { abbData={...}, invoiceData={...}} abbData Object { service="24", conn_fee="0", month_fee="249", more...} invoiceData ...

Angular-Slickgrid displaying empty data entries

Currently, I am attempting to implement a grid option in my application using the angular slickgrid library. Despite referencing the wiki page for guidance on displaying the grid, I am facing the issue of no data appearing in the grid, and there are no err ...

The Dropbox picker is now launching in a new tab instead of a new window when using Chrome

I am encountering an issue with opening Dropbox picker in a new modal window. It works perfectly in all browsers except for Google Chrome. Is there anyone who can guide me on why it opens in a new tab in Chrome? Is there a parameter in options that I can ...

Angular ng-repeat not populating the list properly, causing a collapse not to display

Currently, I am working on developing an app using Angular.js and Bootstrap UI, but I have run into a problem with a collapse navigation feature. The issue I am facing is that I have an ng-repeat that should be functioning properly. However, when I click ...

Encountering an error while running npm install - package.json data parsing failed

Encountering an error during npm install on Windows 10, using node v6.10.3 and npm v3.10.10 Please assist in resolving this issue. Error message: npm ERR! npm v3.10.10 npm ERR! file C:\angular2-helloworld\package.json npm ERR! code EJSONPARSE ...

Enhancing functionality by integrating Jquery/JS with input fields and labels

I am currently facing a challenge in applying CSS to the label element when the corresponding input is selected. After attempting and failing to use input:checked + label due to limitations in the HTML structure that cannot be altered, I seek alternative ...

Ways to retrieve information beyond the scope of the 'then' method

One issue I am facing involves a piece of code that is only accessible inside of the 'then' function. I need to access it outside of this block in order to utilize it in other parts of my program. $scope.model = {'first_name':'&ap ...

Typescript: Extracting data from enum items using types

I am facing a challenge with an enum type called Currency. I am unable to modify it because it is automatically generated in a graphql schema. However, I need to utilize it for my data but I'm unsure of how to go about doing so. enum Currency { rub ...

Session storage causes NodeJs, Apollo, and typescript server to stall and become unresponsive

As a newcomer to NodeJs, I've been following Ben Awad's full-stack tutorial on YouTube. You can check it out here. Everything was working fine after setting up my server. I added express-session for session storage and connected it to Redis usin ...

When invoked, the function Subscribe() does not have a

Currently, I am facing an issue where I cannot use the result obtained from subscribe() outside of the subscribe function. Whenever I try to console.log the result, it always shows up as undefined. My suspicion is that this might be related to the asynch ...

The PrimeNG Tree component offers a range of unique features

Encountering an issue with the PrimeNG tree in angular2 Let's take a look at the code snippet from product_tree.component.ts : constructor(private http: HttpClient, private productsService: ProductsService) { this.productsService.getProductsClasse ...

Error TS 2322 - The property 'id' is not present in the object of type '{ id: number'

Just starting out with Angular and TypeScript. I created a model with the same properties but encountered an error and am struggling to find a solution: TS2322: Type '{ id: number; model: string; plate: string; deliveryDate: string; deadline: st ...

How to retrieve an array from a JSON object with JavaScript

After receiving an object from the server, I am specifically looking to extract the array ITEMS. How can I achieve this? I attempted using array['items'] but it did not yield the expected result and returned undefined { "items": [ { ...

Loading dynamic images in HTML using Javascript and Django templates

Attempting to load a specific image using javascript within a django template has presented challenges due to the formatting of django tags. The standard django static asset source in an img tag looks like this: {% load static %} <img src="{% static & ...

Having difficulty refreshing metadata on the client side within Next.js through client-side data retrieval

Having some trouble with updating metadata using NextSeo when fetching data on the client side. useEffect(()=>{ fetch(assetURL) .then((res) => res.json()) .then((data) => { console.log(data); }) .catch((error) => { console.err ...

Instructions on how to insert a hyperlink into the information within the generated div utilizing an API

Currently, I am fetching information from an API based on the user's input (zipcode). The data retrieved includes the name of the institution, address, and webpage. I've been trying to make the webpage link clickable by adding a hyperlink to the ...

A more efficient method for querying documents based on ids that are not in a given list and then sorting them by a specific publish date

After implementing the code provided below, I noticed that the performance tests indicate each request takes a second or longer to complete. My goal is to enhance this speed by at least 10 times. The bottleneck seems to be caused by the NOT operator resu ...

Firebase cloud function encountered an issue: Error: EISDIR - attempting to perform an unauthorized operation on a directory

I am currently working on a task that involves downloading an image from a URL and then uploading it to my Firebase cloud storage. Below is the code I have implemented for this process. import * as functions from 'firebase-functions'; import * a ...

Determine the duration/length of an audio file that has been uploaded to a React application

I am working on a React web application built with create-react-app that allows users to upload songs using react-hook-forms. The uploaded songs are then sent to my Node/Express server via axios. I want to implement a feature that calculates the length of ...

The first click does not trigger the update for the md-autocomplete

After successfully implementing md-autocomplete in my Angular4 app, I encountered a problem where the options do not show up when the list is first clicked, unlike in the demo. The options only appear once a selection is made. Here is the HTML code: &l ...