如何在表单中包含自定义组件?

时间:2018-03-25 16:33:42

标签: angular angular5 angular-components

我有一个名为“Employee-type”的组件(包括一个select组件),它将用于显示相应的员工列表(datagrid)。 如何在表单中重复使用相同的组件,如下所示,具有有效,无效,脏,触摸等额外功能?

enter image description here

1 个答案:

答案 0 :(得分:0)

我使用@ angular / material mat-select创建了一个简单的可重用选择组件。查看live demo

MY-select.component.ts

import { Component, Input } from '@angular/core';
import { FormControl } from '@angular/forms';

@Component({
  selector: 'my-select',
  template: `
  <mat-form-field>
    <mat-select [formControl]="ctrl" [placeholder]="placeholder">
      <mat-option *ngFor="let option of options" [value]="option">
        {{ option }}
      </mat-option>
    </mat-select>
  </mat-form-field>
  `,
  styles: [`:host { display: block; }`]
})
export class MySelectComponent  {
  @Input() ctrl: FormControl;
  @Input() options: string[];
  @Input() placeholder: string;
}

使用示例:

app.component.html

<form [formGroup]="form">
    <my-select [ctrl]="form.get('cities')" [options]="cities" placeholder="Cities"></my-select>
    <my-select [ctrl]="form.get('countries')" [options]="countries" placeholder="Countries"></my-select>
</form>

app.component.ts

import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  form: FormGroup;

  cities = ['Krakow', 'Warszawa', 'Gdansk'];
  countries = ['Poland', 'Germany', 'Sweden'];

  constructor(private fb: FormBuilder) {
    this.form = this.fb.group({
      cities: ['', Validators.required],
      countries: ['', Validators.required],
    })
  }
}