如何将 NgIF 条件与 formcontrol 而不是 ngModel 一起使用



我想用我的formcontrol比较我的值而不是使用ngModel,当我在我的输入框中输入值时,我想显示我的取消图像,所以我在订阅中给出了userTextValue为true,我现在的查询是如何在单击取消时重置值。我希望输入框为空,现在取消按钮已隐藏但仍可用值,我正在使用管道过滤值。

<input matInput class="form-control input" placeholder="Enter name or Id" id="user"
[formControl]="userControl"[matAutocomplete]="auto>
<img src="assets/icons/cancel.svg" *ngIf="userTextvalue" class="cancel-icon" 
aria-label="Clear" (click)="clearUserValues()">

TS:

constructor() {
this.userControl.valueChanges.subscribe((user) => {
this.filterResult = user;
this.userTextvalue = true;
});
}
clearUserValues() { 
this.filterResult = "";
this.userTextvalue = false;
}

管道.ts

import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'filterUser'
})
export class FilterUserPipe implements PipeTransform {
transform(items: any[], searchText: string): any[] {
if (searchText && searchText.length > 1) {
items = searchText ? this.filterUsers(items, searchText) : items.slice();
} else {
items = [];
}
return items;
}
filterUsers(items: any[], value: string): any[] {
const filterValue = value.toLowerCase();
return items.filter(item => item.name.toLowerCase().indexOf(filterValue) === 0);
}
}

首先,您必须了解模板驱动和响应式表单方法之间的区别。当 formcontrol 发生任何更改时,它会返回新的表单对象(包括其 formcontrols(,这就是使其成为同步方法的原因。
让我用简短的场景来总结一下。

当表单控件输入或 html 标记发生任何更改时 可以通过订阅它来跟踪它。 例如 获取特定的表单控件更改值。 表单:表单组

this.form.get('name of your formControl').subscribe(value => {// here (value) is changed value of that particular formControl. });

第二种方法 例如,您可以在任何可单击的输入按钮或选择输入上设置表单控件。 然后,您可以在事件单击时发出一个方法,在该方法上,您可以订阅更改的值并将其比较或保存到所需的位置。 示例代码 ::::

<mat-select formControlName="transferType"> <mat-option [value]="type" *ngFor="let type of transferTypes" (click)="onChanges()">{{type}}</mat-option> </mat-select>

当我选择一个选项时,我正在调用"onChanges(("方法,然后我正在订阅此表单控件并获取更改值并通过比较操作来比较所选值。

就像您可以获取更改的值然后将其设置为任何布尔类型变量一样,然后您可以在 HTML 模板中使用*ngIf=""语句设置任何div/

如果有任何困惑,请告诉我。 谢谢。。

棱角7 #reactiveforms #formcontrol

根据您的问题,我不完全确定为什么要使用过滤器,因为您尚未显示代码。但是,如果只想重置控件,请在clearUserValues()方法中将this.filterResult = ""更改为this.userControl.setValue('')

另外,由于您正在订阅 值更改,因此最好在ngOnInit().

在此处查看堆栈闪电战

您的 TS 代码将是这样的。

ngOnInit() {
this.onchanges();}
onchanges() {
this.form.get('userControl').valueChanges.subscribe( data => {
// here you can set your boolean value for condition to show cancel button
and push the value/or object which you take from input textbox in an your array for further comparison. 
});}
clearUserValues() { 
// here you will be set your boolean for hiding cancel button 
and then you will be set empty state to your formControl input by doing like this.
this.form.get('userControl').patchValue(//here you will be pass empty string '' or what ever you want set it to.);}

最新更新