Updated answer
use a custom directive to make the focus happen! then the solution will work!
directive
import { ElementRef } from '@angular/core';
import { Directive } from '@angular/core';
@Directive({
selector: '[appFocusOnLoad]',
})
export class FocusOnLoadDirective {
constructor(private elementRef: ElementRef) {}
ngOnInit() {
if (this.elementRef) {
this.elementRef.nativeElement.focus();
}
}
}
forked stackblitz
Below is an example of using blur
for select and datepicker, select works great but for datepicker, you need to combine dateChange
and blur
to get the blur event during select and focus out!
html
<mat-form-field appearance="fill">
<mat-label>Input & change events</mat-label>
<input
matInput
[matDatepicker]="picker"
(blur)="blur()"
(dateChange)="blur()"
/>
<mat-hint>MM/DD/YYYY</mat-hint>
<mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
<mat-datepicker #picker></mat-datepicker>
</mat-form-field>
<mat-form-field>
<mat-select (blur)="blur()" placeholder="Fav Animal">
<mat-option *ngFor="let option of options" [value]="option">
{{ option }}
</mat-option>
</mat-select>
</mat-form-field>
<!-- Copyright 2022 Google LLC. All Rights Reserved.
Use of this source code is governed by an MIT-style license that
can be found in the LICENSE file at https://angular.io/license -->
ts
import { Component } from '@angular/core';
import { FormControl } from '@angular/forms';
/** @title Basic datepicker */
@Component({
selector: 'datepicker-overview-example',
templateUrl: 'datepicker-overview-example.html',
})
export class DatepickerOverviewExample {
constructor() {}
options = ['Cat', 'Dog', 'Lion'];
selectedCountry: string = 'GB';
selectedCountryControl = new FormControl(this.selectedCountry);
blur() {
console.log('blurred');
}
}
/** Copyright 2022 Google LLC. All Rights Reserved.
Use of this source code is governed by an MIT-style license that
can be found in the LICENSE file at https://angular.io/license */
forked stackblitz