创建可重用的matAutocomplete指令

时间:2017-11-01 17:54:44

标签: angular angular-material2

我想实现一个与Angular Material autocomplete component一起使用的组件或指令。但是,我很难弄清楚如何封装业务逻辑并将其连接起来,同时仍然暴露输入元素,因此很容易设置样式并增加可访问性。

理想情况下,我希望有一个可以添加到输入中的指令,但我的理解是您需要实例化<mat-autocomplete>组件。因此,我尝试创建一个组件来实例化<mat-option>列表。

@Component({
  selector: 'employee-search',
  exportAs: 'employeeSearch',
  template: `
    <mat-option *ngFor="let employee of employees | async" [value]="employee.globalId">
      <span>
        <span>{{ employee.name }}</span> |
        <small>{{ employee.globalId }}</small>
      </span>
    </mat-option>
  `,
})
export class EmployeeComponent implements OnInit {
  control = new FormControl();
  employees: Observable<any[]>;

  constructor(private rest: MyRestService) { }

  ngOnInit() {
    this.employees = this.control.valueChanges
    .filter((value: string) => value && value.length >= 3)
    .debounceTime(300)
    switchMap((value: string) => this.loadEmployees(value));
  }

  loadEmployees(searchInput: string): Observable<any[]> {
    return this.rest.get('/employees', { filter: searchInput });
  }
}

我已尝试在<mat-autocomplete>组件中使用此组件,它似乎正在进行http调用以加载数据,但选项未加载。

<mat-form-field>
  <input matInput placeholder="Employee" aria-label="Employee"
      [matAutocomplete]="auto"
      [formControl]="employee.control">
</mat-form-field>
<mat-autocomplete #auto="matAutocomplete">
  <employee-search #employee="employeeSearch"></employee-search>
</mat-autocomplete>

如何创建组件或指令以使输入显示我的自定义自动完成列表?

1 个答案:

答案 0 :(得分:0)

我通过包装<mat-autocomplete>并将其传递给输入来实现这一点。

@Component({
  selector: 'employee-search',
  exportAs: 'employeeSearch',
  template: `
    <mat-autocomplete>
      <mat-option *ngFor="let employee of employees | async" [value]="employee.globalId">
        <span>
          <span>{{ employee.name }}</span> |
          <small>{{ employee.globalId }}</small>
        </span>
      </mat-option>
    </mat-autocomplete>
  `,
})
export class EmployeeComponent implements OnInit {
  control = new FormControl();
  employees: Observable<any[]>;

  @ViewChild(MatAutocomplete) autocomplete: MatAutocomplete;

  constructor(private rest: MyRestService) { }

  ngOnInit() {
    this.employees = this.control.valueChanges
    .filter((value: string) => value && value.length >= 3)
    .debounceTime(300)
    switchMap((value: string) => this.loadEmployees(value));
  }

  loadEmployees(searchInput: string): Observable<any[]> {
    return this.rest.get('/employees', { filter: searchInput });
  }
}

然后使用模板引用变量,我能够访问控件和自动完成属性。

<mat-form-field>
  <input matInput placeholder="Employee" aria-label="Employee"
      [matAutocomplete]="employee.autocomplete"
      [formControl]="employee.control">
</mat-form-field>
<employee-search #employee="employeeSearch"></employee-search>