PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label angular-material. Show all posts
Showing posts with label angular-material. Show all posts

Tuesday, August 2, 2022

[FIXED] How can I apply custom styles to the mat-menu content?

 August 02, 2022     angular, angular-material, html-table     No comments   

Issue

I use the mat-menu for filtering the columns in the custom table component. In the mat-menu I have a search input which I want to style. I have tried:

class
panelClass
backdropClass

but with no success. I want to point out that if I put the styles in the main style.scss file the css is applied to the input field. But I want to solve it in another way, putting the css in the components file. Here is my code:

<mat-menu #menu>
    <div fxLayout="row wrap" fxFlex="100">
      <div stop-propagation fxFlex="90" fxFlexOffset="5">
        <div class="input-container">
          <input id="inputSearch" class="search-input" type="text" autocomplete="off"
            placeholder="{{ 'Ricerca...' | translate }}" [(ngModel)]="searchValue" (keyup)="filterValue(col.key)">
        </div>
        <mat-selection-list class="selectList" #select [id]="col.key"
          (selectionChange)="selecteChange($event, col.key)" class="maxHeight300">
          <ng-container *ngIf="conditionsList && conditionsList.length > 0; else noOptions">
            <mat-list-option color="primary" [checkboxPosition]="'before'" *ngFor="let condition of conditionsList"
              [value]="condition">
              {{ condition }}
            </mat-list-option>
          </ng-container>
          <ng-template #noOptions>
            <span fxLayoutAlign="center center" [innerHTML]="'Nessun risultato' | translate"></span>
          </ng-template>
        </mat-selection-list>
      </div>
      <div fxFlex="90" fxFlexOffset="5" fxLayout="row" fxLayoutAlign="space-between center"
        *ngIf="conditionsList && conditionsList.length > 0" class="marginBottom10">
        <button fxFlex="49" mat-raised-button (click)="clearColumn(col.key)">Pulisci</button>
        <button fxFlex="49" mat-raised-button color="primary" (click)="applyFilter(col.key)">Filtra</button>
      </div>
    </div>
  </mat-menu>

and the css

.search-input {
    width: 100%;
    -webkit-transition: -webkit-box-shadow 0.3s;
    transition: -webkit-box-shadow 0.3s;
    transition: box-shadow 0.3s;
    transition: box-shadow 0.3s, -webkit-box-shadow 0.3s;
    font-size: 16px;
    line-height: 22px;
    padding: 10px;
    background-color: white;
    border-radius: 6px;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    display: block;
    border: 1px solid grey;
    box-shadow: 0px 4px 8px 0px rgb(0 0 0 / 10%), 0px 2px 5px 0px rgb(0 0 0 / 8%);      
}

Solution

As per comments from question:

Due to how MatMenu (and CdkOverlay in general, which is used underneath) is instantiated, styles have to be scoped globally for them to affect things rendered in the overlay. They can be placed in different file, but they have to pierce the component level in some way.

This means that one can style it with one of the below:

  • Use ::ng-deep (which is deprecated, but still working) selector to pierce the component
  • Use ViewEncapsulation.None to promote the component stylesheet to the global level
  • Place styles in the global styles.scss

An example using ::ng-deep with styles from the question are provided in the stacblitz here.



Answered By - TotallyNewb
Answer Checked By - Pedro (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Monday, August 1, 2022

[FIXED] How to add pagination in angular material table that bind to API response

 August 01, 2022     angular, angular-material, pagination     No comments   

Issue

I'm new to angular. In my project shown list of products and its work correctly.

My HTML code is below :

<table mat-table [dataSource]="list_product" style="width: 20%;">
    <!-- id Column -->
    <ng-container matColumnDef="id" style="width: 20%;">
        <th mat-header-cell *matHeaderCellDef style="align-items: center;"> id </th>
        <td mat-cell *matCellDef="let list_product"> {{list_product.id}} </td>
    </ng-container>

    <!-- description Column -->
    <ng-container matColumnDef="description">
        <th mat-header-cell *matHeaderCellDef> Name </th>
        <td mat-cell *matCellDef="let list_product"> {{list_product.description}} </td>
    </ng-container>

    <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
    <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
<mat-paginator [pageSizeOptions]="[5, 10, 20]" showFirstLastButtons></mat-paginator>

and my TypeScript code is -

import { Component, OnInit,ViewChild } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { analyzeAndValidateNgModules } from '@angular/compiler';
import { MatPaginator} from '@angular/material/paginator';
import { MatTableDataSource} from '@angular/material/table';

@Component({
    selector: 'app-basic',
    templateUrl: './basic.component.html',
    styleUrls: ['./basic.component.scss']
})
export class BasicComponent implements OnInit {

    public list_product:any=[];
    displayedColumns: string[] = ['id', 'description'];
    @ViewChild(MatPaginator) paginator: MatPaginator;

    constructor(private http:HttpClient) { }

    ngOnInit(): void {
        this.get_data();
        this.list_product.paginator = this.paginator;
    }

    get_data(){
        this.http.get<any>("http://localhost:3000/listp").subscribe(
            res => this.list_product = res
        )
    }
}

Pagination does not work and all of list are shown. Pagination buttons does not work in html file.


Solution

For client side pagination, the MatTableDataSource has pagination, sorting and filtering functionality built-in to it.

Follow the steps below -

  1. Use MatTableDataSource type as the dataSource and initialize it with an empty array
  2. Set the data property of MatTableDataSource once data is received
  3. Get a reference of the table's paginator with @ViewChild
  4. Implement AfterViewInit to set the paginator property of MatTableDataSource once the view is initialized

Your final component code should look something like -

export class BasicComponent implements OnInit, AfterViewInit {
    
    public list_product = new MatTableDataSource<any>([]);  // <-- STEP (1)
    displayedColumns: string[] = ['id', 'description'];
    @ViewChild(MatPaginator) private paginator: MatPaginator;  // <-- STEP (3)

    constructor(private http:HttpClient) { }

    ngOnInit(): void {
        this.get_data();
    }

    get_data(){
        this.http.get<any>("http://localhost:3000/listp").subscribe(
            res => this.list_product.data = res  // <-- STEP (2)
        );
    }
    
    ngAfterViewInit(): void {
        this.list_product.paginator = this.paginator;  // <-- STEP (4)
    }
}

You should explore the documentation for further details.



Answered By - atiyar
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Sunday, July 31, 2022

[FIXED] how to scroll to top in material table on paginate change

 July 31, 2022     angular, angular-material, pagination     No comments   

Issue

I am stuck in an issue where in material table, I click on next button, the scroll stays to bottom , whereas it should scroll to top.

<mat-table class="table-container" fxFlex="100" [dataSource]="allUsersDataSource">
  <ng-container matColumnDef="firstName">
    <mat-header-cell fxFlex="25" *matHeaderCellDef> First Name </mat-header-cell>
    <mat-cell fxFlex="25" *matCellDef="let element"> {{element.first_name}} </mat-cell>
  </ng-container>

  <ng-container matColumnDef="lastName">
    <mat-header-cell fxFlex="25" *matHeaderCellDef> Last Name </mat-header-cell>
    <mat-cell fxFlex="25" *matCellDef="let element"> {{element.last_name}} </mat-cell>
  </ng-container> 
     
  <mat-header-row *matHeaderRowDef="allUsersColumns; sticky: true"></mat-header-row>
  <mat-row *matRowDef="let row; columns: allUsersColumns;"></mat-row>
</mat-table>

<mat-paginator #allUsersPaginator [pageSizeOptions]="[25,50,100]" (page)="onAllUserPaginateChange($event)"
    [length]="allUserPagination.length" [pageSize]="25" showFirstLastButtons></mat-paginator>

This is the code behind

onAllUserPaginateChange(event: any) {
  window.scroll(0,0);
}

Solution

Here I gave an ID to the table

eg.

<mat-table id ="matTable" class="table-container" 
  [dataSource]="allUsersDataSource">
<mat-table>

and in the paginate method of that table in the typescript file.

onAllUserPaginateChange(event: any) {
  const matTable= document.getElementById('matTable');
  matTable.scrollTop = 0;
}


Answered By - Chetan Birajdar
Answer Checked By - Willingham (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] how to make click event when i click next or select page size with "mat-paginator " in angular

 July 31, 2022     angular, angular-material, pagination     No comments   

Issue

I am developing a webpage and i have to show list of items with pagination for an api . show when i select a pagesize or click to next page i have to click a method in ts file . but i don't know how to do it . .

html

   <mat-paginator 
    [pageSizeOptions]="[5, 10, 15, 20]"
    [pageSize]="5"
    aria-label="Select page"
    
    ></mat-paginator>

ts file

  searchData:responsebody[] =[];
 dataSource!: MatTableDataSource<any>;
 dataObs$!: Observable<any>;
  ngOnInit(): void {

    this.setPagination();
  
  }

  setPagination() {
    this.dataSource = new MatTableDataSource<any>(this.searchData);
    this._changeDetectorRef.detectChanges();
    this.dataSource.paginator = this.paginator;
    this.dataObs$ = this.dataSource.connect();
  }


//

nextpageData(pagesize:number,index:number){


}

so when i slect page size or click next page i want to call this method "nextpageData(param1,param2)"

enter image description here


Solution

mat-paginator has a page event:

Event emitted when the paginator changes the page size or page index.

<mat-paginator (page)="yourHandler($event)"></mat-paginator>


Answered By - Eugene
Answer Checked By - Willingham (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to persist Angular mat-paginator data?

 July 31, 2022     angular, angular-material, pagination, paginator     No comments   

Issue

Our project have over ten tables with different types of data. For each table we already use mat-paginator to pagination goals. Now I want to add persistence so next time user open one of tables he/she could view data sorted in the same way as he/she has sorted it the previous time.

I could not find any information about persistence feature for mat-paginator on official Angular Material site.

Could someone point me out how is it better to implement such functionality in Angular?


Solution

If you take a look at the API tab of the mat paginator documentation you can see it accepts pageIndex and pageSize as inputs.

I would go ahead and use this part of the mat-paginator API to set the page size and page index to my liking. I would then go ahead and save the state of my paginators in localStorage or sessionStorage (depending on the persistence needs), then read the values I need on page load and set up the paginators.



Answered By - Octavian Mărculescu
Answer Checked By - Willingham (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Saturday, July 23, 2022

[FIXED] How can we create a sidenav bar that is responsive using only angular material?

 July 23, 2022     angular, angular-material, bootstrap-4, mdbootstrap, sidebar     No comments   

Issue

Can I use Angular materials 4 to create a similar behavior of the following sidenav example made with mdbootstrap: the link shows a responsive sidenav with buttons with lists.

I don't want to use bootstrap 4 as it needs to add javascript and jQuery libraries for most of the components. And mdbootstrap uses jquery in some features.

If there is any other libraries, feel free to mention it.


Solution

If you combine the angular material sidenav and expansion panel components, you should be able to replicate the same design and functionality.

This is a quick example by simply copying a expansion panel into a responsive sidenav (both examples from angular material):

https://stackblitz.com/edit/angular-akre5x?file=app/sidenav-responsive-example.html



Answered By - pfeileon
Answer Checked By - Marie Seifert (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Friday, March 18, 2022

[FIXED] i generate ng material data table using schematic. i tried replacing their dummy data with data from api, but couldn't get it done

 March 18, 2022     angular, angular-material, php, phpmyadmin     No comments   

Issue

this is the interface Tickets[]

export interface Tickets {
    name: string;
    id: number;
  }

this is the service i created that should return data fetched from API.. but here i hard coded the data (please someone should help me with right function that will return the data from api in getData() function)

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { Tickets } from './ticket.model'

@Injectable({
  providedIn: 'root'
})
export class OpenTicketsService {
  private _url:string = 'assets/data.json';

  constructor(private http: HttpClient) { }

  dataRequest():Observable<Tickets[]>{
    return this.http.get<Tickets[]>(this._url);

  }

  getData(){
    //to be replace with the code that will subscribe to `dataRequest()` and return the data
    return [
      {id: 1, name: 'Hydrogen'},
      {id: 2, name: 'Helium'},
      {id: 3, name: 'Lithium'},
      {id: 4, name: 'Beryllium'},
      {id: 5, name: 'Boron'},
      {id: 6, name: 'Carbon'},
      {id: 7, name: 'Nitrogen'},
      {id: 8, name: 'Oxygen'},
      {id: 9, name: 'Fluorine'},
      {id: 10, name: 'Neon'},
    ];
  }

this is datasource.ts file generated along with angular material data-table

import { DataSource } from '@angular/cdk/collections';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { map } from 'rxjs/operators';
import { Observable, of as observableOf, merge } from 'rxjs';
import { OpenTicketsService } from './open-tickets.service';
import { Tickets } from './ticket.model';


export class TicketsTableDataSource extends DataSource<Tickets> {

//this is the function that will return the data from OpenTicketsService and assign it to "data"

 data: Tickets[] = this.ticketService.getData();
  paginator: MatPaginator;
  sort: MatSort;

  constructor(private ticketService:OpenTicketsService) {
    super();
  }

  connect(): Observable<Tickets[]> {
    const dataMutations = [
      observableOf(this.data),
      this.paginator.page,
      this.sort.sortChange
    ];

    return merge(...dataMutations).pipe(map(() => {
      return this.getPagedData(this.getSortedData([...this.data]));
    }));
  }

  disconnect() {}

  private getPagedData(data: Tickets[]) {
    const startIndex = this.paginator.pageIndex * this.paginator.pageSize;
    return data.splice(startIndex, this.paginator.pageSize);
  }

  private getSortedData(data: Tickets[]) {
    if (!this.sort.active || this.sort.direction === '') {
      return data;
    }

    return data.sort((a, b) => {
      const isAsc = this.sort.direction === 'asc';
      switch (this.sort.active) {
        case 'name': return compare(a.name, b.name, isAsc);
        case 'id': return compare(+a.id, +b.id, isAsc);
        default: return 0;
      }
    });
  }
}

function compare(a: string | number, b: string | number, isAsc: boolean) {
  return (a < b ? -1 : 1) * (isAsc ? 1 : -1);
}

component.ts file that will display the data on the component.html

import { AfterViewInit, Component, OnInit, ViewChild } from '@angular/core';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { MatTable } from '@angular/material/table';
import { TicketsTableDataSource } from './tickets-table-datasource';
import { Tickets } from './ticket.model';
import { OpenTicketsService } from './open-tickets.service';

@Component({
  selector: 'app-tickets-table',
  templateUrl: './tickets-table.component.html',
  styleUrls: ['./tickets-table.component.scss']
})
export class TicketsTableComponent implements AfterViewInit, OnInit {
  constructor(private ticketService:OpenTicketsService) { }
  @ViewChild(MatPaginator) paginator: MatPaginator;
  @ViewChild(MatSort) sort: MatSort;
  @ViewChild(MatTable) table: MatTable<Tickets>;
  dataSource: TicketsTableDataSource;

  /** Columns displayed in the table. Columns IDs can be added, removed, or reordered. */
  displayedColumns = ['id', 'name'];

  ngOnInit() {
    this.dataSource = new TicketsTableDataSource(this.ticketService);
  }

  ngAfterViewInit() {
    this.dataSource.sort = this.sort;
    this.dataSource.paginator = this.paginator;
    this.table.dataSource = this.dataSource;
  }
}

Solution

the data source can not be a "service"!!

Futhermore, you needn't use ngAfterView and a View Child to give all properties to your table, see the example in the docs

I suppose you want to write some like

ngAfterViewInit() {
    this.tickerService.dataRequest().subscribe(res=>{
       this.dataSource = new TicketsTableDataSource(res);
       this.dataSource.sort = this.sort;
       this.dataSource.paginator = this.paginator;
       this.table.dataSource = this.dataSource;
    })
  }

See that it's all under subcribe function

NOTE: If you use {static:true} you can asign the paginator in ngOnInit



Answered By - Eliseo
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home
View mobile version

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing