*ngIf hide some content on mobile screen, Angular 4

后端 未结 9 2072
盖世英雄少女心
盖世英雄少女心 2020-12-13 04:47

I have:

showHide: false;

Content
相关标签:
9条回答
  • 2020-12-13 05:16

    You can use window.screen.width. Example:

    ngOnInit() {
      if (window.screen.width === 360) { // 768px portrait
        this.mobile = true;
      }
    }
    

    Html:

    <button *ngIf="mobile" (click)="showHide = !showMap"></button>
    
    0 讨论(0)
  • 2020-12-13 05:18

    Use the below code into the OnInit()

    inMobile:boolean = false
    ngOnInit() {
      if (window.screen.width === 360) {
        this.isMobile = true;
      }
    }
    

    by using above code we can put two css; based on desktop and mobile:-

    <button *ngIf="mobile">Close</button>
    

    or

    <button [class.button]="!isMobile" [class.button-mobile]="isMobile">Close</button>
    

    CSS:

    .button{
    margin-left:100px;
    }
    .button-mobile{
    margin-left:50px;
    }
    
    0 讨论(0)
  • 2020-12-13 05:20

    For future me or others if you need a solution that monitors the screen size and are using Observables/rxjs then this solution works:

    ngOnInit(): void {
      // Checks if screen size is less than 1024 pixels
      const checkScreenSize = () => document.body.offsetWidth < 1024;
    
      // Create observable from window resize event throttled so only fires every 500ms
      const screenSizeChanged$ = Observable.fromEvent(window, 'resize').throttleTime(500).map(checkScreenSize);
    
      // Start off with the initial value use the isScreenSmall$ | async in the
      // view to get both the original value and the new value after resize.
      this.isScreenSmall$ = screenSizeChanged$.pipe(startWith(checkScreenSize()))
    }
    
    0 讨论(0)
提交回复
热议问题