我试图向我的 mat-form-field 输入字段添加(模糊)和(焦点)效果,但它们似乎在我这边无法正常运行。
这是一个与我类似的代码示例:
html 文件
<form class="example-form">
<mat-form-field class="example-full-width" appearance="outline">
<mat-label *ngIf="isFieldFocused">Selected Food</mat-label>
<input
matInput
placeholder="Select Menu"
(focus)="click($event)"
(blur)="inActive($event)"
/>
</mat-form-field>
</form>
打字稿文件
export class InputOverviewExample {
isFieldFocused: boolean = false;
click($event) {
if ($event) {
this.isFieldFocused = true;
}
}
inActive() {
this.isFieldFocused = $event ? true : false;
}
}
由于这段代码,当我专注于 mat-form-field 时,它没有显示 mat-label。谁能建议我的方法可能有什么问题或提供替代解决方案?
--
我试图实现的是最初显示占位符。然后,当输入字段获得焦点时,它应该显示 mat-label。这可能吗?预先感谢您!
工作正常,问题是
*ngIf
弄乱了动画,而是选择[hidden]
,它也隐藏了值但不会破坏它,动画似乎也可以工作!
<mat-label [hidden]="!isFieldFocused">Selected Food</mat-label>
import { Component } from '@angular/core';
import { MatSelectModule } from '@angular/material/select';
import { MatInputModule } from '@angular/material/input';
import { MatFormFieldModule } from '@angular/material/form-field';
import { FormGroup, ReactiveFormsModule, FormControl } from '@angular/forms';
import { tap, debounceTime } from 'rxjs/operators';
import { merge } from 'rxjs';
import { CommonModule } from '@angular/common';
/** @title Simple form field */
@Component({
selector: 'form-field-overview-example',
templateUrl: 'form-field-overview-example.html',
styleUrl: 'form-field-overview-example.css',
standalone: true,
imports: [
MatFormFieldModule,
CommonModule,
MatInputModule,
MatSelectModule,
ReactiveFormsModule,
],
})
export class FormFieldOverviewExample {
isFieldFocused: boolean = false;
click($event: any) {
console.log('focus');
if ($event) {
this.isFieldFocused = true;
}
}
inActive($event: any) {
this.isFieldFocused = false;
}
}
<form class="example-form">
<mat-form-field class="example-full-width" appearance="outline">
<mat-label [hidden]="!isFieldFocused">Selected Food</mat-label>
<input
matInput
placeholder="Select Menu"
(focus)="click($event)"
(blur)="inActive($event)"
/>
</mat-form-field>
</form>