Basic Syntax in python3

Variables in Python3

counter = 100          # An integer assignment
miles   = 1000.0       # A floating point
name    = "John"       # A string

print (counter)
print (miles)
print (name)

a = b = c = 1

print(a,b,c)

x, y, z = 1, 2, "john"

print(x,y,z)

del x,y,z

Output :

Arithmetic Operation in Python3

a = 2
b = 3
print(a + b)
print(a - b)
print(a * b)
print(b / a)
print(b % a)
print(a ** b)
print(b // a)

Output :

Python Comparison Operator :

a = 10
b = 20
print(" a == b : {0}".format(a==b))
print(" a != b : {0}".format(a!=b))
print(" a > b : {0}".format(a>b))
print(" a < b : {0}".format(a<b))
print(" a >= b : {0}".format(a>=b))
print(" a <= b : {0}".format(a<=b))

Output :

Python Logical Operators

a = True
b = False
print (a and b)
print (a or b)

Output :

Membership operator in Python

a = 10
b = 20
list = [20,40,60]

if(a in list):
    print("{0} is present in list".format(a))
else:
    print("{0} is not present in list".format(a))

if(b in list):
    print("{0} is present in list".format(b))
else:
    print("{0} is not present in list".format(b))

Output :

is Operator in Python

a = 20
b = 20
if (a is b):
    print('Id of a and b are same : a id : ',id(a),' b id : ',id(b))
else:
    print('Id of a and b are not same : a id : ',id(a),' b id : ',id(b)))

Output :

If elif else in Python3

amount = 2000

if amount<1000:
   discount = amount*0.05
   print ("Discount",discount)
elif amount<5000:
   discount = amount*0.10
   print ("Discount",discount)
else:
   discount = amount*0.15
   print ("Discount",discount)
    
print ("Net payable:",amount-discount)

Output :

Basics of Spring Security

  • Spring security handles the application level security.
  • Spring security handles some of the basic security out of the box when added to the application
    • Login and Logout functionality.
    • Allow/Block access to URLs to logged in users.
    • Allow/Block access to URLs to logged in users and with certain rules.
    • Handles common vulnerabilities.
  • Thus helping application developers to worry less about security and can focus more on development on application,
  • Functionalities that Spring Security offer :
    • Username and password authentication.
    • SSO / OKTA / LDAP
    • App level authorization
    • Intra app authorization like OAuth
    • Microservice security (using token, JWT)
    • Method level secuirty
  • 5 Core Concepts of Spring Security
    • Authentication.
      • Knowledge based Authentication – Done by some user unique data, possibility an id and password
      • Possession based Authentication – Phone call or text msg for OTP or keycard or badges
      • Note : Multiple Authentication can be used as well (Example : 2FA : Two Factor Authentication)
    • Authorization
      • Checking if user has access to do what is he suppose to do is called Authorization.
    • Principal
      • Principal is user who you have already identified by using Authentication i.e principal is the currently logged in user or an account.
    • Granted Authority
      • Fine grain permission of a particular user.
    • Roles
      • Roles are Group of Authorities that are assigned together

Download a File using Angular and SpringBoot

We need to install node package called file save to run below demo :

npm i -s file-saver

Note : In below example we are downloading file from the resource folder but we can also make a file download by giving its path.

Spring Boot Changes are below :

package CsrfSpringDemo;

import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
public class HelloGradleController {

	@GetMapping("/api/helloList")
	public List<String> helloList(){
		List<String> x = new ArrayList<>();
		x.add("Hello");
		x.add("world");
		return x;
	}
	@GetMapping("/api/download")
	public void downloadFile(String fileName, HttpServletResponse res) throws Exception {
		res.setHeader("Content-Disposition","attachment; filename="+fileName);
		res.getOutputStream().write(contentOf(fileName));
	}
	private byte[] contentOf(String fileName) throws Exception{
		return Files.readAllBytes(Paths.get(getClass().getClassLoader().getResource(fileName).toURI()));
	}
}

Angular Changes are below :

app.component.html

Hello World
{{data | json}}
<button (click)="download('hello.txt')">Download</button>

app.component.ts

import { Component, OnInit } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { saveAs } from 'file-saver';

const MIME_TYPE = {
  pdf: 'application/pdf',
  txt: 'application/text'
}

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{
  title = 'CsrfDemo';
  data: string;
  constructor(private http: HttpClient){

  }
  ngOnInit(): void {
    this.http.get<string>("/api/helloList").subscribe(
      res => { console.log(res); this.data = res; },
      err => { console.log(JSON.stringify(err)); },
      () => { console.log('Api Call completed'); }
    );
  }

  download(dataFileName) {
    const extn = dataFileName.substr(dataFileName.lastIndexOf('.')+1);
    const REQUEST_PARAMS = new HttpParams().set('fileName', dataFileName);
    const REQUEST_URI = '/api/download';
    this.http.get(REQUEST_URI,{
      params: REQUEST_PARAMS,
      responseType: 'arraybuffer'
    }).subscribe(
      data => {
        saveAs(new Blob([data],{type: MIME_TYPE[extn]}),dataFileName);
      }
    );
  }
}

Custom Validation using group and MessageSource in SpringBoot

Directory Structure

build.gradle

plugins {
    id 'java'
    id 'org.springframework.boot' version '2.0.5.RELEASE'
    id 'io.spring.dependency-management' version '1.0.7.RELEASE'
}

repositories {
    jcenter()
}

dependencies {
    implementation 'com.google.guava:guava:28.0-jre'
    testImplementation 'junit:junit:4.12'
    implementation 'org.springframework.boot:spring-boot-dependencies:2.0.5.RELEASE'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
	compile 'javax.validation:validation-api:2.0.1.Final'
    

    components {
        withModule('org.springframework:spring-beans') {
            allVariants {
                withDependencyConstraints {
                    it.findAll { it.name == 'snakeyaml' }.each { it.version { strictly '1.19' } }
                }
            }
        }
    }
}

bootJar {
    mainClassName = 'GradleDemo.App'
}

task runJar{
	dependsOn 'assemble'
	dependsOn 'jar'
	doLast{
  		javaexec { 
    		main="-jar";
    		args = [
            	"build/libs/"+rootProject.name+".jar"
           	]
		} 
	}
}

settings.gradle

rootProject.name = 'SpringBoot'

application.properties

server.port=9090
logging.level.org.springframework=DEBUG

messages.properties

date.connot.future=Date of birth cannot be future dateddddddddddddd

CreateUserGroup.java

package app;

public interface CreateUserGroup { }

User.java

package app;

import java.util.Date;

import javax.validation.constraints.Past;
import javax.validation.constraints.Size;

public class User {
	
	private Integer id;
	
	@Size(min=2,message="Size cannot be less than 2")
	private String name;
	
	@Past(message = "{date.connot.future}",groups = {CreateUserGroup.class})
	private Date birthDate;
	
	public User() {
		 
	}
	
	public User(Integer id, String name, Date birthDate) {
		super();
		this.id = id;
		this.name = name;
		this.birthDate = birthDate;
	}
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Date getBirthDate() {
		return birthDate;
	}
	public void setBirthDate(Date birthDate) {
		this.birthDate = birthDate;
	}
}

HelloGradleController.java

package app;

import java.net.URI;

import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

@RestController
@CrossOrigin
public class HelloGradleController {
    
    @PostMapping("/createUser")
    public ResponseEntity<Object> createUser(@Validated({CreateUserGroup.class}) @RequestBody User user){
    	URI location = ServletUriComponentsBuilder
    						.fromCurrentRequest()
    						.path("/{id}")
    						.buildAndExpand(user.getId()).toUri();
    	return ResponseEntity.created(location).build();
    }

}

App.java

/*
 * This Java source file was generated by the Gradle 'init' task.
 */
package app;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;

@SpringBootApplication
public class App {

    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }
    @Bean
    public MessageSource messageSource() {
        ReloadableResourceBundleMessageSource messageSource
          = new ReloadableResourceBundleMessageSource();
         
        messageSource.setBasename("classpath:messages");
        messageSource.setDefaultEncoding("UTF-8");
        return messageSource;
    }
    
    @Bean
    public LocalValidatorFactoryBean getValidator() {
        LocalValidatorFactoryBean bean = new LocalValidatorFactoryBean();
        bean.setValidationMessageSource(messageSource());
        return bean;
    }
}

ErrorField.java

package app.exception;

public class ErrorField {
	private String errorMessage;
	private String field;
	
	public ErrorField(){
		
	}
	
	public ErrorField(String errorMessage, String field) {
		super();
		this.errorMessage = errorMessage;
		this.field = field;
	}

	public String getErrorMessage() {
		return errorMessage;
	}

	public void setErrorMessage(String errorMessage) {
		this.errorMessage = errorMessage;
	}

	public String getField() {
		return field;
	}

	public void setField(String field) {
		this.field = field;
	}	
}

ExceptionResponse.java

package app.exception;

import java.util.Date;
import java.util.List;

public class ExceptionResponse {
	private Date timestamp;
	private String message;
	private String details;
	private List<ErrorField> errorFieldList;
	
	public ExceptionResponse(Date timestamp, String message, String details, List<ErrorField> errorFieldList) {
		super();
		this.timestamp = timestamp;
		this.message = message;
		this.details = details;
		this.errorFieldList = errorFieldList;
	}

	public Date getTimestamp() {
		return timestamp;
	}

	public void setTimestamp(Date timestamp) {
		this.timestamp = timestamp;
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	public String getDetails() {
		return details;
	}

	public void setDetails(String details) {
		this.details = details;
	}

	public List<ErrorField> getErrorFieldList() {
		return errorFieldList;
	}

	public void setErrorFieldList(List<ErrorField> errorFieldList) {
		this.errorFieldList = errorFieldList;
	}
}

AppExceptionHandling.java

package app.exception;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

@ControllerAdvice
@RestController
public class AppExceptionHandling extends ResponseEntityExceptionHandler {

	@Override
	protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex,
			HttpHeaders headers, HttpStatus status, WebRequest request) {
		List<ErrorField> errorFieldList = new ArrayList<>();
		for (FieldError fieldError : ex.getBindingResult().getFieldErrors()) {
			ErrorField errorField = new ErrorField(fieldError.getDefaultMessage(), fieldError.getField());
			errorFieldList.add(errorField);
		}
		ExceptionResponse exceptionResponse = new ExceptionResponse(new Date(), ex.getMessage(),
				ex.getBindingResult().toString(), errorFieldList);
		return new ResponseEntity(exceptionResponse, HttpStatus.BAD_REQUEST);
	}

}

Output :

Reactive Forms with Validations

First we need to add angular material to the project

ng add @angular/material

Create a module to handle all material imports and exports

ng g m material

Now follow the code below :

material.module.ts

import { NgModule } from '@angular/core';
import { MatButtonModule, MatInputModule, MatSelectModule, MatCheckboxModule, MatChipsModule} from '@angular/material';

const MaterialComponent = [
  MatButtonModule,
  MatInputModule,
  MatSelectModule,
  MatCheckboxModule,
  MatChipsModule
];

@NgModule({
  imports: [
    MaterialComponent
  ],
  exports: [
    MaterialComponent
  ]
})
export class MaterialModule { }

app.module.ts

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

import { AppComponet } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { MaterialModule } from './material/material.module';
import { ReactiveFormsModule } from '@angular/forms';

@NgModule({
  declarations: [
    AppComponet
  ],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    MaterialModule,
    ReactiveFormsModule
  ],
  providers: [],
  bootstrap: [AppComponet]
})
export class AppModule { }

app.component.ts

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponet implements OnInit {
  myForm: FormGroup;
  success = false;

  constructor(private fb: FormBuilder){ }

  ngOnInit(): void {
    this.myForm = this.fb.group({
      email: ['', [
        Validators.required,
        Validators.email
      ]],
      message: ['', [
        Validators.required,
        Validators.minLength(5),
        Validators.pattern('[a-zA-Z]+')
      ]],
      age: ['', [
        Validators.required,
        Validators.minLength(2), //Minimum lengh of String is 2
        Validators.min(18),
        Validators.max(65)
      ]]
/*       agree: [false, [
        Validators.requiredTrue
      ]] */
    });
    this.myForm.valueChanges.subscribe(console.log);
  }

  get email() {
    return this.myForm.get('email');
  }
  get message() {
    return this.myForm.get('message');
  }
  get age() {
    return this.myForm.get('age');
  }

  submitForm(){
    this.success=true;
  }
}

app.component.html

<form [formGroup]="myForm" [hidden]="success" (ngSubmit)="submitForm()">
  Value: {{myForm.value | json}}
  <hr/>
  <mat-form-field>
    <input matInput placeholder="Email Id" formControlName="email"/>
    <mat-error *ngIf="email.invalid &amp;&amp; email.touched">
      Email id is inValid
    </mat-error>
  </mat-form-field>

  <mat-form-field>
    <input matInput placeholder="Message" formControlName="message"/>
    <mat-error *ngIf="message.touched &amp;&amp; message.errors?.minlength">
      Minimum Length if 5
    </mat-error>
    <mat-error *ngIf="message.touched &amp;&amp; message.errors?.pattern">
      Invalid Pattern
    </mat-error>
    <mat-hint align="end">Must have one characters only</mat-hint>
  </mat-form-field>

  <mat-form-field>
    <input matInput formControlName="age" placeholder="Age"/>
    <mat-hint align="end">Enter your age</mat-hint>
    <mat-error *ngIf="age.touched &amp;&amp; age.errors?.required">
      This field is madatory
    </mat-error>
    <mat-error *ngIf="age.touched &amp;&amp; age.errors?.min">
      {{age.errors.min.actual}} you are too young to use this app kiddo!
    </mat-error>
    <mat-error *ngIf="age.touched &amp;&amp; age.errors?.max">
      {{age.errors.max.actual}} you are too old to use this app gramps!
    </mat-error>
  </mat-form-field><br/>
  <button type="submit" mat-raised-button [disabled]="myForm.invalid">Submit</button>
</form>
<div *ngIf="success" class="notification is-success">
  Yay! We received your submission
</div>

Output :

Reusable Material Data Table as a component

A new component is created with the name of table

ng g c table

table.component.ts

import { Component, OnInit, Input, ViewChild } from '@angular/core';
import { MatPaginator } from '@angular/material/paginator';

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

  @ViewChild(MatPaginator, {static: true}) paginator: MatPaginator;
  @Input() displayedColumns: string[];
  @Input() columnHeader: string[];
  @Input() dataSource;
  @Input() itemsPerPage: number;
  @Input() columnWidth: number[];
  pageSizeOptions: [number];
  public customeCss = [];
  constructor() { }

  ngOnInit() {
    this.dataSource.paginator = this.paginator;
    this.pageSizeOptions = [this.itemsPerPage];
    this.calculateCustomeCss();
  }
  calculateCustomeCss(){
    for (const width of this.columnWidth) {
      this.customeCss.push({
        flex: '0 0 ' + width + 'px'
      });
    }
  }
}

table.component.html


<mat-grid-list cols="3" rowHeight="9:1" style="background:rgb(192, 143, 143); border: solid 2px #000;">
  <mat-grid-tile style="background-color: royalblue;">Logo</mat-grid-tile>
  <mat-grid-tile colspan="2"></mat-grid-tile>
  <mat-grid-tile colspan="3">
    <div class="mat-display-1" style="margin-bottom: 0px;"><u>Periodic Table</u></div>
  </mat-grid-tile>
  <mat-grid-tile colspan="3" rowspan="2">
    <div class="mat-body-1">
    Detail 1 : Text1<br/>
    Detail 1 : Text1<br/>
    Detail 1 : Text1<br/>
  </div>
  </mat-grid-tile>
</mat-grid-list>
<mat-card>
  <mat-card-content>
  <mat-table [dataSource]="dataSource" class="mat-elevation-z8">
    <ng-container *ngFor="let col of displayedColumns; let i = index" [matColumnDef]="col">
      <mat-header-cell
        *matHeaderCellDef
        mat-sort-header [innerHTML]="columnHeader[i]"
        [ngStyle]="customeCss[i]"
        ></mat-header-cell>
      <mat-cell *matCellDef="let element"
        [ngStyle]="customeCss[i]"
       > {{ element[col] }} </mat-cell>
    </ng-container>
    <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
    <mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
  </mat-table>
</mat-card-content>
  <mat-card-footer>
    <mat-paginator [pageSizeOptions]="pageSizeOptions" showFirstLastButtons></mat-paginator>
  </mat-card-footer>
</mat-card>

table.component.css

table {
  width: 100%;
}

app.component.ts

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

export interface PeriodicElement {
  name: string;
  position: number;
  weight: number;
  symbol: string;
}

const ELEMENT_DATA: PeriodicElement[] = [
  {position: 1, name: 'Hydrogen', weight: 1.0079, symbol: 'H'},
  {position: 2, name: 'Helium', weight: 4.0026, symbol: 'He'},
  {position: 3, name: 'Lithium', weight: 6.941, symbol: 'Li'},
  {position: 4, name: 'Beryllium', weight: 9.0122, symbol: 'Be'},
  {position: 5, name: 'Boron', weight: 10.811, symbol: 'B'},
  {position: 6, name: 'Carbon', weight: 12.0107, symbol: 'C'},
  {position: 7, name: 'Nitrogen', weight: 14.0067, symbol: 'N'},
  {position: 8, name: 'Oxygen', weight: 15.9994, symbol: 'O'},
  {position: 9, name: 'Fluorine', weight: 18.9984, symbol: 'F'},
  {position: 10, name: 'Neon', weight: 20.1797, symbol: 'Ne'},
];

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  displayedColumns: string[] = ['position', 'name', 'weight', 'symbol'];
  columnHeader: string[] = ['No', 'Name', 'Weight', 'Symbol'];
  dataSource = new MatTableDataSource(ELEMENT_DATA);
  itemsPerPage = 5;
  columnWidth = [80, 180, 180, 100];
}

app.component.html

<app-table
  [displayedColumns]="displayedColumns"
  [columnHeader]="columnHeader"
  [columnWidth]="columnWidth"
  [dataSource]="dataSource"
  [itemsPerPage]="itemsPerPage">
</app-table>

material.module.ts (A new module is created for material)

import { NgModule } from '@angular/core';
import { MatButtonModule,
  MatDividerModule,
  MatGridListModule,
  MatFormFieldModule,
  MatInputModule,
  MatTableModule,
  MatCardModule
  } from '@angular/material';
import { MatProgressSpinnerModule} from '@angular/material/progress-spinner';
import { MatBadgeModule } from '@angular/material/badge';
import { MatButtonToggleModule} from '@angular/material/button-toggle';
import { MatIconModule} from '@angular/material/icon';
import { MatToolbarModule} from '@angular/material/toolbar';
import { MatSidenavModule} from '@angular/material/sidenav';
import { MatMenuModule} from '@angular/material/menu';
import { MatListModule } from '@angular/material/list';
import { MatPaginatorModule } from '@angular/material/paginator';


const MaterialComponent = [
  MatButtonModule,
  MatButtonToggleModule,
  MatIconModule,
  MatBadgeModule,
  MatProgressSpinnerModule,
  MatToolbarModule,
  MatSidenavModule,
  MatMenuModule,
  MatListModule,
  MatDividerModule,
  MatGridListModule,
  MatFormFieldModule,
  MatInputModule,
  MatTableModule,
  MatPaginatorModule,
  MatCardModule
];

@NgModule({
  imports: [
    MaterialComponent,
  ],
  exports: [
    MaterialComponent
  ]
})
export class MaterialModule { }

app.module.ts

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

import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { MaterialModule } from './material/material.module';
import { FormsModule } from '@angular/forms';
import { TableComponent } from './table/table.component';


@NgModule({
  declarations: [
    AppComponent,
    TableComponent
  ],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    MaterialModule,
    FormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]

Output :

Angular Material Input – A form component

material.module.ts

import { NgModule } from '@angular/core';
import { MatButtonModule, MatDividerModule, MatGridListModule, MatFormFieldModule, MatInputModule } from '@angular/material';
import { MatProgressSpinnerModule} from '@angular/material/progress-spinner';
import { MatBadgeModule } from '@angular/material/badge';
import { MatButtonToggleModule} from '@angular/material/button-toggle';
import { MatIconModule} from '@angular/material/icon';
import { MatToolbarModule} from '@angular/material/toolbar';
import { MatSidenavModule} from '@angular/material/sidenav';
import { MatMenuModule} from '@angular/material/menu';
import { MatListModule } from '@angular/material/list';


const MaterialComponent = [
  MatButtonModule,
  MatButtonToggleModule,
  MatIconModule,
  MatBadgeModule,
  MatProgressSpinnerModule,
  MatToolbarModule,
  MatSidenavModule,
  MatMenuModule,
  MatListModule,
  MatDividerModule,
  MatGridListModule,
  MatFormFieldModule,
  MatInputModule
];

@NgModule({
  imports: [
    MaterialComponent,
  ],
  exports: [
    MaterialComponent
  ]
})
export class MaterialModule { }

app.module.ts

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

import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { MaterialModule } from './material/material.module';
import { FormsModule } from '@angular/forms';


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

app.component.html

<div>
  <mat-form-field>
    <input matInput>
  </mat-form-field>
</div>
<div>
  <mat-form-field> <!-- flatLabel="auto" which is default -->
    <mat-label>Name</mat-label>
    <input matInput>
  </mat-form-field>
</div>
<div>
  <mat-form-field floatLabel="never">
    <mat-label>Name</mat-label>
    <input matInput>
  </mat-form-field>
</div>
<div>
  <mat-form-field floatLabel="always">
    <mat-label>Name</mat-label>
    <input matInput>
  </mat-form-field>
</div>
<div>
  <mat-form-field>
    <mat-label>On Focus Hint</mat-label>
    <input matInput (focus)="focusState = true" (focusout)="focusState = false">
    <mat-hint  *ngIf="focusState">Hello hint</mat-hint>
  </mat-form-field>
</div>
<!-- For multiple fields
  <div *ngFor="let item of array">
  <input #item name="date" type="text" (focus)="item.alt = true" (focusout)="item.alt = false">
  <mat-hint align="end" *ngIf="item.alt">Max 50 characters</mat-hint>
</div> -->
<div>
  <mat-form-field floatLabel="always">
    <mat-label>Name</mat-label>
    <input matInput required>
  </mat-form-field>
</div>
<div>
  <mat-form-field floatLabel="always" hideRequiredMarker>
    <mat-label>Name</mat-label>
    <input matInput required>
  </mat-form-field>
</div>
<div>
  <mat-form-field floatLabel="always" hideRequiredMarker color="accent">
    <mat-label>Name</mat-label>
    <input matInput required>
    <mat-hint>Min 5 characters</mat-hint>
  </mat-form-field>
</div>
<div>
  <mat-form-field floatLabel="always" hideRequiredMarker color="warn"> <!-- apperance is legacy here -->
    <mat-label>Name</mat-label>
    <input matInput required>
    <mat-hint align="end">Min 5 characters</mat-hint>
  </mat-form-field>
</div>
<div>
  <mat-form-field floatLabel="always" hideRequiredMarker apperance="standard">
    <mat-label>Name</mat-label>
    <input matInput required>
    <mat-hint align="end">Min 5 characters</mat-hint>
  </mat-form-field>
</div>
<div>
  <mat-form-field floatLabel="always" hideRequiredMarker apperance="fill">
    <mat-label>Name</mat-label>
    <input matInput required>
    <mat-hint align="end">Min 5 characters</mat-hint>
  </mat-form-field>
</div>
<div>
  <mat-form-field floatLabel="always" hideRequiredMarker apperance="outline">
    <mat-label>Name</mat-label>
    <input matInput required>
    <mat-hint align="end">Min 5 characters</mat-hint>
  </mat-form-field>
</div>

app.component.ts

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  focusState: boolean;
}

Output :