如何将我的 Angular Material 字段设置为只读?我查看了他们的 props 文档,没有看到任何与只读字段相关的内容。
我将“readonly:true”作为道具添加到我的 component.ts 文件中的 Formly 字段中,但无法看到渲染表单中反映的更改。
app.component.ts
import {Component} from '@angular/core';
import {FormGroup} from '@angular/forms';
import {FormlyFieldConfig} from '@ngx-formly/core';
@Component({
selector: 'app',
template: `
<form [formGroup]="form" (ngSubmit)="onSubmit(model)">
<formly-form [form]="form" [fields]="fields" [model]="model"></formly-form>
<button type="submit" class="btn btn-default">Submit</button>
</form>
`,
})
export class AppComponent {
form = new FormGroup({});
model = { email: '[email protected]' };
fields: FormlyFieldConfig[] = [
{
key: 'email',
type: 'input',
props: {
label: 'Email address',
placeholder: 'Enter email',
required: true,
}
}
];
onSubmit(model) {
console.log(model);
}
}
app.component.html
<form [formGroup]="form" (ngSubmit)="onSubmit(model)">
<formly-form [form]="form" [fields]="fields" [model]="model"></formly-form>
<button type="submit" class="btn btn-default">Submit</button>
</form>
在最新版本的
formly
中,可以使用options的formState
属性来传入readOnly
属性。
options: FormlyFormOptions = {
formState: { readonly: true },
};
然后在表单定义属性
expressions
中使用此属性并更新 readonly
属性。
expressions: {
'props.readonly': 'formState.readonly',
},
我正在使用信号来实现
readOnly
的反应切换,但您可以使用传统的角度方法。 effect
对信号变化做出反应并更新选项。
import { Component, computed, effect, Signal, signal } from '@angular/core';
import { FormGroup } from '@angular/forms';
import { FormlyFormOptions, FormlyFieldConfig } from '@ngx-formly/core';
@Component({
selector: 'formly-app-example',
templateUrl: './app.component.html',
standalone: false,
})
export class AppComponent {
readOnly = signal(false);
form = new FormGroup({});
model = { email: '[email protected]' };
fields: FormlyFieldConfig[] = [
{
key: 'email',
type: 'input',
expressions: {
'props.readonly': 'formState.readonly',
},
templateOptions: {
label: 'Email address',
placeholder: 'Enter email',
required: true,
},
},
];
computedOptions = {
formState: { readonly: this.readOnly() },
};
constructor() {
effect(() => {
this.computedOptions.formState.readonly = this.readOnly();
});
}
toggle() {
this.readOnly.update((value) => !value);
}
onSubmit() {
alert(JSON.stringify(this.model, null, 4));
}
}
<button type="button" class="btn btn-primary" (click)="toggle()">
{{ readOnly() ? 'edit' : 'readOnly' }}
</button>
<form [formGroup]="form" (ngSubmit)="onSubmit()">
<formly-form
[model]="model"
[fields]="fields"
[options]="computedOptions"
[form]="form"
></formly-form>
<button type="submit" class="btn btn-primary">Submit</button>
</form>