通过按下按钮动态更改 ngModel - Angular

Dynamically changing ngModel from button presses - Angular

我有这段代码允许用户按特定字段进行过滤:

<input type="text" class = "form-control" [(ngModel)]="siteFilter.site_name">
<button type="button"  class="btn btn-default">Address</button>
<button type="button"  class="btn btn-default">Site</button>
<button type="button"  class="btn btn-default">Phone</button>

在 component.ts 文件中:

siteFilter: any = { site_name: '', address:'', phone:'' };

我有 3 个按钮,应根据单击哪个按钮更改 ngModel.xxx,以便它按相应字段进行过滤。

我尝试使用一个包含各个字段的数组,单击按钮会 select 索引,但它只是打印出字符串值而不是将其绑定到该模型。

类似于您发布的代码

尽量保持原来的结构:您的按钮可以更改过滤器类型,点击后 - 清除其他过滤器。

模板

<input type="text" [(ngModel)]="siteFilter[filterType]">

<button type="button"  class="btn btn-default" (click)="changeFilter('address')">Address</button>
<button type="button"  class="btn btn-default" (click)="changeFilter('site_name')">Site</button>
<button type="button"  class="btn btn-default" (click)="changeFilter('phone')">Phone</button>

分量

siteFilter;
filterType = 'site_name';

constructor() {
  this.name = `Angular! v${VERSION.full}`
  this.emptySiteFilter();
}

changeFilter(newFilter) {
  this.emptySiteFilter();
  this.filterType = newFilter;
}

emptySiteFilter() {
  this.siteFilter = { site_name: '', address:'', phone:'' };
}

Live plunker demo

备选单选按钮

尽管如果是我,我会使用一个单选按钮和一个可以更改类型的对象。

模板

<input type="text" [(ngModel)]="filter.value" />

<input type="radio" name="filter" [(ngModel)]="filter.type" value="address"> Address
<input type="radio" name="filter" [(ngModel)]="filter.type" value="site_name"> Site
<input type="radio" name="filter" [(ngModel)]="filter.type" value="phone"> Phone

分量

filter = { type: 'site', value: '' }

Alternative plunker that uses radio buttons