Categories
Angular Material

Angular Material — Checkbox and Datepickers

Angular Material is a popular UI framework based on Material Design for Angular.

In this article, we’ll look at how to use Angular Material into our Angular project.

Checkbox

We can add checkboxes with Angular Material.

For example, we can write:

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { MatCheckboxModule } from '@angular/material/checkbox';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    BrowserAnimationsModule,
    MatCheckboxModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  checked = false;
  indeterminate = false;
  disabled = false;

constructor() { }
}

app.component.html

<div>
  <section class="example-section">
    <mat-checkbox class="example-margin" [(ngModel)]="checked">Checked
    </mat-checkbox>
    <mat-checkbox class="example-margin" [(ngModel)]="indeterminate">
      Indeterminate</mat-checkbox>
  </section>
</div>

We added the MatCheckboxModule and then add the variables to bind the checked values of the checkbox to with ngModel .

Chips

We can add chips to add small containers for some short information.

For example, we can write:

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { MatChipsModule } from '@angular/material/chips';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    BrowserAnimationsModule,
    MatChipsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

app.component.html

<div>
  <mat-chip-list aria-label="Fish selection">
    <mat-chip>One fish</mat-chip>
    <mat-chip>Two fish</mat-chip>
    <mat-chip color="primary" selected>Primary fish</mat-chip>
    <mat-chip color="accent" selected>Accent fish</mat-chip>
  </mat-chip-list>
</div>

We add the MatChipsModule to add the chips.

Then in the template, we add the mat-chip-list component as the container for chips.

mat-chip is the chip.

Datepicker

Angular Material comes with a date picker.

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { MatDatepickerModule } from '@angular/material/datepicker';
import { MatNativeDateModule } from '@angular/material/core';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatButtonModule } from '@angular/material/button';
import { MatInputModule } from '@angular/material/input';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    BrowserAnimationsModule,
    MatDatepickerModule,
    MatNativeDateModule,
    MatFormFieldModule,
    MatButtonModule,
    MatInputModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

app.component.html

<div>
  <mat-form-field class="example-full-width" appearance="fill">
    <mat-label>Choose a date</mat-label>
    <input matInput [matDatepicker]="picker">
    <mat-datepicker #picker></mat-datepicker>
  </mat-form-field>
  <button mat-raised-button (click)="picker.open()">Open</button>
</div>

We imported the MatDatepickerModule , MatNativeDateModule , MatFormfieldModule , MatButtonModule , and MatInputModule to so that we can add the date picker into our app.

In the template, we add the mat-form-field to use as the date picker container,.

mat-label has the label.

input has the input.

mat-datepicker has the date picker.

Also, we have a button to call picker.open() to open the date picker.

Conclusion

We can add a checkbox and date picker with Angular Material.

Categories
Angular Material

Angular Material — Button Toggles and Cards

Angular Material is a popular UI framework based on Material Design for Angular.

In this article, we’ll look at how to use Angular Material into our Angular project.

Button Toggle

We can add button toggles with the MatButtonToggleModule .

For example, we can write:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { MatButtonToggleModule } from '@angular/material/button-toggle';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    BrowserAnimationsModule,
    MatButtonToggleModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

app.component.html

<div>
  <mat-button-toggle-group name="fontStyle">
    <mat-button-toggle value="bold">Bold</mat-button-toggle>
    <mat-button-toggle value="italic">Italic</mat-button-toggle>
    <mat-button-toggle value="underline">Underline</mat-button-toggle>
  </mat-button-toggle-group>
</div>

We add the MatButtonToggleModule into app.module.ts .

Then we can use the mat-button-toggle-group with the mat-button-toggle to add the button toggle.

We can change the appearance with the appearance attribute:

<div>
  <mat-button-toggle-group name="fontStyle" appearance="legacy">
    <mat-button-toggle value="bold">Bold</mat-button-toggle>
    <mat-button-toggle value="italic">Italic</mat-button-toggle>
    <mat-button-toggle value="underline">Underline</mat-button-toggle>
  </mat-button-toggle-group>
</div>

Card

Cards are containers that we can put elements in.

For example, we can write:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { MatCardModule } from '@angular/material/card';
import { MatButtonModule } from '@angular/material/button';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    BrowserAnimationsModule,
    MatCardModule,
    MatButtonModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

app.component.html

<div>
  <mat-card class="example-card">
    <mat-card-header>
      <div mat-card-avatar class="example-header-image"></div>
      <mat-card-title>Shiba Inu</mat-card-title>
      <mat-card-subtitle>Dog Breed</mat-card-subtitle>
    </mat-card-header>
    <img mat-card-image
      src="https://material.angular.io/assets/img/examples/shiba2.jpg"
      alt="Photo of a Shiba Inu">
    <mat-card-content>
      <p>
        The Shiba Inu
      </p>
    </mat-card-content>
    <mat-card-actions>
      <button mat-button>LIKE</button>
      <button mat-button>SHARE</button>
    </mat-card-actions>
  </mat-card>
</div>

We add the MatCardModule to add a card.

Then we add the mat-card for the main card container.

mat-card-header is the card header.

mat-card-title has the title.

mat-card-subtitle has the subtitle.

The mat-card-image directive is used to add an image into the card.

mat-card-content has the main card content.

mat-card-actions has the actions for the card.

Conclusion

We can add button toggles and cards into our Angular app with Angular Material.

Categories
Angular Material

Angular Material — Badges, Bottom Sheets, and Buttons

Angular Material is a popular UI framework based on Material Design for Angular.

In this article, we’ll look at how to use Angular Material into our Angular project.

Badges

We can add badges into our app with Angular Material.

To add it, we write:

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { MatBadgeModule } from '@angular/material/badge';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    BrowserAnimationsModule,
    MatBadgeModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

app.component.html

<div>
  <span matBadge="4" matBadgeOverlap="false">Text with a badge</span>
</div>

We add the matBadge and matBadgeOverlap properties to add a badge.

Also, we can make it raised:

app.component.html

<div>
  <span mat-raised matBadge="4" matBadgeOverlap="false">Text with a badge</span>
</div>

Bottom Sheet

A bottom sheet adds a panel to the bottom of the screen.

For example, we can use it by writing:

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { MatBottomSheetModule } from '@angular/material/bottom-sheet';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    BrowserAnimationsModule,
    MatBottomSheetModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

app.component.ts

import { Component } from '@angular/core';
import { MatBottomSheet, MatBottomSheetRef } from '@angular/material/bottom-sheet';

@Component({
  selector: 'bottom-sheet-overview-example-sheet',
  template: 'bottom sheet',
})
export class BottomSheetOverviewExampleSheet {
  constructor(private _bottomSheetRef: MatBottomSheetRef<BottomSheetOverviewExampleSheet>) {}

  openLink(event: MouseEvent): void {
    this._bottomSheetRef.dismiss();
    event.preventDefault();
  }
}

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  constructor(private _bottomSheet: MatBottomSheet) { }

  openBottomSheet(): void {
    this._bottomSheet.open(BottomSheetOverviewExampleSheet);
  }
}

app.component.html

<div>
  <button mat-raised-button (click)="openBottomSheet()">Open file</button>
</div>

We added a button to that calls the openBottomSheet method to open the bottom sheet.

In app.component.ts , we added a BottomSheetOverviewExampleSheet component to show the sheet.

We have the openBottomSheet method to show the sheet.

We inject the _bottomSheet service so that we can open the bottom sheet.

Button

We can add buttons with the MatButtonModule .

For instance, we can write:

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { MatButtonModule } from '@angular/material/button';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    BrowserAnimationsModule,
    MatButtonModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

app.component.html

<div>
  <button mat-button color="primary">Primary</button>
  <button mat-raised-button color="primary">Primary</button>
</div>

We add the mat-button and mat-raised-button directives to add Material design buttons.

Conclusion

We can add badges, bottom sheets, and buttons with Angular Material easily.

Categories
Angular Material

Angular Material — Getting Started

Angular Material is a popular UI framework based on Material Design for Angular.

In this article, we’ll look at how to use Angular Material into our Angular project.

Getting Started

We can install Angular Material into an existing project by running:

ng add @angular/material

Then we run:

ng serve

to serve our app.

Autocomplete

Angular comes with an autocomplete component.

To use it, we write:

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { MatAutocompleteModule } from '@angular/material/autocomplete';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    BrowserAnimationsModule,
    MatAutocompleteModule,
    MatFormFieldModule,
    ReactiveFormsModule,
    FormsModule,
    MatInputModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

app.component.ts

import { Component } from '@angular/core';
import { FormControl } from '@angular/forms';
import { Observable } from 'rxjs';
import { map, startWith } from 'rxjs/operators';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  myControl = new FormControl();
  options = [
    { name: 'apple' },
    { name: 'orange' },
    { name: 'grape' }
  ];
  filteredOptions: Observable<any[]>;

  ngOnInit() {
    this.filteredOptions = this.myControl && this.myControl.valueChanges
      .pipe(
        startWith(''),
        map(value => typeof value === 'string' ? value : value.name),
        map(name => name ? this._filter(name) : this.options.slice())
      );
  }

  displayFn(user): string {
    return user && user.name ? user.name : '';
  }

  private _filter(name: string) {
   const filterValue = name.toLowerCase();

   return this.options.filter(option => option.name.toLowerCase().indexOf(filterValue) === 0);
  }
}

app.component.html

<div>
  <form class="example-form">
    <mat-form-field class="example-full-width">
      <mat-label>Assignee</mat-label>
      <input type="text" matInput [formControl]="myControl"
        [matAutocomplete]="auto">
      <mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn">
        <mat-option *ngFor="let option of filteredOptions | async"
          [value]="option">
          {{option.name}}
        </mat-option>
      </mat-autocomplete>
    </mat-form-field>
  </form>
</div>

We add the input and the mat-autocomplete component into the mat-form-field to show the input and the autocomplete.

In app.component.ts , we watch the value of myControl and then do the filtering with the map operator and the filter method.

The displayFn method is bused to display the values for the autocomplete.

We also have to import all the required modules in app.module.ts .

We can also add a custom input into the mat-form-field component.

Also, we defined a FormControl and set it to the input to let us watch the input value.

For instance, we write:

app.component.ts

import { Component } from '@angular/core';
import { FormControl } from '@angular/forms';
import { Observable } from 'rxjs';
import { map, startWith } from 'rxjs/operators';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  control = new FormControl();
  fruits: string[] = ['apple', 'orange', 'grape'];
  filteredFruits: Observable<string[]>;

ngOnInit() {
    this.filteredFruits = this.control.valueChanges.pipe(
      startWith(''),
      map(value => this._filter(value))
    );
  }

  private _filter(value: string): string[] {
    const filterValue = this._normalizeValue(value);
    return this.fruits.filter(street => this._normalizeValue(street).includes(filterValue));
  }

  private _normalizeValue(value: string): string {
    return value.toLowerCase().replace(/s/g, '');
  }
}

app.component.html

<div>
  <form class="example-form">
    <input type="text" placeholder="Search a fruit" [formControl]="control"
      [matAutocomplete]="auto">
    <mat-autocomplete #auto="matAutocomplete">
      <mat-option *ngFor="let street of filteredFruits | async"
        [value]="street">
        {{street}}
      </mat-option>
    </mat-autocomplete>
  </form>
</div>

We added our own input into the form instead of a mat-form-field .

Conclusion

We can add an autocomplete with Angular Material.

Categories
JSON

Working with JSON — Using Fetch API with React

JSON stands for JavaScript Object Notation.

It’s a popular data-interchange format that has many uses.

In this article, we’ll take a look at how to use JSON with React and Fetch API.

Making HTTP Requests with React

React is a view library, so it doesn’t come with any way to make HTTP requests.

To do this, we have to use our own HTTP client library.

Most modern browsers today comes with the Fetch API.

We can use it with the useEffect hook.

To use it, we can write:

import React, { useEffect, useState } from "react";

export default function App() {
  const [answer, setAnwser] = useState();

  const getAnswer = async () => {
    const res = await fetch("https://yesno.wtf/api");
    const answer = await res.json();
    setAnwser(answer);
  };

  useEffect(() => {
    getAnswer();
  }, []);
  return <div className="App">{JSON.stringify(answer)}</div>;
}

to make a GET request to an endpoint with the fetch function.

It returns a promise that resolves to the data and then we call json to get the data from the JSON.

Then we call setAnswer to set the answer state.

The empty array in 2nd argument means that we only run the callback when the component mounts.

Also, we can move the getAnswer function into its own hook by writing:

import React, { useEffect, useState } from "react";

const useAnswer = () => {
  const [answer, setAnwser] = useState();

  const getAnswer = async () => {
    const res = await fetch("https://yesno.wtf/api");
    const answer = await res.json();
    setAnwser(answer);
  };

  useEffect(() => {
    getAnswer();
  }, []);
  return answer;
};

export default function App() {
  const answer = useAnswer();
  return <div className="App">{JSON.stringify(answer)}</div>;
}

We move all the logic to get the response from the API endpoint to its own hook.

Then we can keep our component squeaky clean with no side effects.

To make a POST request with the Fetch API, we can write:

import React, { useEffect, useState } from "react";

const makeRequest = async (data) => {
  const res = await fetch("https://jsonplaceholder.typicode.com/todos", {
    method: "POST",
    mode: "cors",
    cache: "no-cache",
    credentials: "same-origin",
    headers: {
      "Content-Type": "application/json"
    },
    body: JSON.stringify(data)
  });
  const response = await res.json();
  return response;
};

export default function App() {
  const submit = async () => {
    const res = await makeRequest({
      title: "delectus aut autem",
      completed: false
    });
    console.log(res);
  };

  return (
    <>
      <button onClick={submit}>add todo</button>
    </>
  );
}

We added the makeRequest function that calls fetch with the URL to make the request to an an object with the options for our request.

The method property is the request method.

The mode is the request mode. 'cors' makes a cross-origin request.

cache set to 'no-cache' disables cache.

credentials sets the cookies origin.

headers has the HTTP request headers that we want to send.

body has the HTTP request body.

When we click the ‘add todo’ button, then submit function makes the request with the makeRequest function.

Then the response data is returned with the promise returned from the makeRequest function and logged from the console log.

Conclusion

We make HTTP requests in a React app with the Fetch API.