Reputation: 85
I have a component named "Employee-type" (which includes a select component) which will be used for showing corresponding employees list(datagrid). How do I re-use the same component inside a form as shown below with extra features like valid, invalid, dirty, touched etc.?
Upvotes: 0
Views: 722
Reputation: 16837
I've created a simple reusable select component, using @angular/material mat-select. Checkout out the 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;
}
Example usage:
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],
})
}
}
Upvotes: 1