Hello everyone !
Let’s talk about Angular Material, a super cool UI library created by google that we angular developers love to use in our projects. But …. what if we have been using it wrong ? I get it, some components that the library uses are super simple, just with a copy and paste we can get them working, and the same with more complex elements like the auto complete…. right ?
Lets see some examples:
https://material.angular.io/components/input/overview
<input matInput placeholder="Favorite food" value="Sushi">
Easy enough! we can still change it in a way so we can use it with a reactive form:
TS:
TS:
export class OurComponent implements OnInit {
form: FormGroup;
constructor(fb: FormBuilder){}
ngOnInit() {
this.form = this.fb.group({
sushi: [""],
});
}
}
HTML:
<form [formGroup]="form">
<mat-form-field>
<mat-placeholder>Your Sushi Input</mat-placeholder>
<textarea matInput formControlName="sushi"></textarea>
</mat-form-field>
</form>
Super simple ! But….what happens with something a little bit more complex ?
HTML for Angular Material autocomplete with filter:
<form class="example-form">
<mat-form-field class="example-full-width">
<input type="text" placeholder="Pick one" aria-label="Number" matInput [formControl]="myControl" [matAutocomplete]="auto">
<mat-autocomplete #auto="matAutocomplete">
<mat-option *ngFor="let option of filteredOptions | async" [value]="option">
{{option}}
</mat-option>
</mat-autocomplete> </mat-form-field>
</form>
TS:
export class AutocompleteFilterExample implements OnInit {
myControl = new FormControl();
options: string[] = ['One', 'Two', 'Three'];
filteredOptions: Observable<string[]>; ngOnInit() {
this.filteredOptions = this.myControl.valueChanges
.pipe(
startWith(''),
map(value => this._filter(value))
);
} private _filter(value: string): string[] {
const filterValue = value.toLowerCase(); return this.options.filter(option => {
option.toLowerCase().includes(filterValue));
}
}
}
Still easy to implement… but if we only do it once… lets see what happens if we have more than one :
HTML: