英文:
How to use Pipe in Angular 14 Reactive Forms?
问题
我们正在使用 Angular 响应式表单和管道来格式化数据,在 Angular 9 中运作良好,但升级到 14 后,难道我们不能在 Angular 响应式表单中再使用管道了吗?
期望是,如果用户输入类似 123.45678 的值,我们需要四舍五入并在后面加上 '%' 符号,就像 123.457% 一样。
当用户再次尝试编辑(聚焦时),需要显示数据库的值,例如 123.45678。
在失焦或切出焦点时,需要再次转换,就像 123.457% 一样。
这种情况在 Angular 9 下运作良好,但升级到 14 后出现了问题。
我在 stackblitz 上制作了一个示例。
英文:
We are using Angular Reactive Forms and pipes to format the data, which was working fine with Angular 9, but after upgrade to 14. Can't we use pipe in Angular Reactive Forms anymore?
The expectation is, If the user enters value like 123.45678, we need to round off and suffix with '%' symbol, like 123.457%
When the user tries to edit again (on focus), need to show the database value like 123.45678
on the blur or tab out, need to convert again like 123.457%
This scenario was working fine with Angular 9 but after upgraded to 14.
I've made sample in stackblitz.
答案1
得分: 1
你可以使假的只读组件不与 formControl 关联,因此,请从第二个输入(只读)中删除 formControlName 参数。
第二个建议是你可以从第一个输入中删除设置值
[value]="loanFormGroup.get('interest')?.value"
因为它不会影响到响应式控制。
演示 - https://stackblitz.com/edit/angular-aw9cit-fkxxdu?file=src/app/app.component.html
英文:
You can make the fake read-only component make not linked with formControl
So, remove formControlName param from the second input(read only).
And the second advice is you can delete setting value from the first input
[value]="loanFormGroup.get('interest')?.value"
because it doesn't affect on reactive control
Demo - https://stackblitz.com/edit/angular-aw9cit-fkxxdu?file=src/app/app.component.html
答案2
得分: 0
Nikita,干得好。我注意到的一件事是,在点击回到编辑字段后,需要点击两次以获得焦点。我以你的代码为起点,但添加了一个ViewChild来在切换视图后访问该字段,然后设置焦点。
@ViewChild("maskedInput") maskedInput: ElementRef | undefined;
我还意识到你不需要一个表单值来管理输入状态,所以我只是使用一个属性来跟踪该状态。
editMode: boolean = true;
而不是(在你的StackBlitz示例中):
editInterest: new FormControl(false),
英文:
Nikita, Great work. One thing I noticed is that the focus after clicking back into the edit field needs to be clicked twice. I used your code as a starting point, but added a view child to access the field after toggling the view and then setting the focus.
@ViewChild("maskedInput") maskedInput : ElementRef | undefined;
toggleToUnMaskedMode(state: boolean) {
this.editMode = state;
setTimeout(() => {
state ? this.maskedInput?.nativeElement.focus() : null;
}, 0);
}
I also realized that you didn't need a form value to manage the state of the inputs so I just used a property to track that state.
editMode: boolean = true;
instead of (in your stackblitz example):
editInterest: new FormControl(false),
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论