I developed a basic reusable component in the following way:
Typescript (TS)
import {Component, Input, OnInit} from '@angular/core';
import {FormControl} from '@angular/forms';
@Component({
selector: 'app-select',
templateUrl: './select.component.html',
styleUrls: ['./select.component.css']
})
export class SelectComponent implements OnInit {
@Input() control: FormControl;
@Input() label: string;
@Input() options: [];
@Input() idAndForAttributes: string;
@Input() customClass: string;
constructor() { }
ngOnInit() {
}
}
HTML
<div class="form-group" [ngClass]="{'invalid': control.invalid && control.touched && control.dirty}">
<label [attr.for]="idAndForAttributes">{{ label }}:</label>
<select class="form-control" [ngClass]="customClass" [formControl]="control" [attr.id]="idAndForAttributes">
<option value="0">- Select -</option>
<option *ngFor="let item of options" [ngValue]="item.id">{{item.description}}</option>
</select>
<ng-container *ngIf="control.dirty && control.touched && control.invalid">
<div *ngIf="control.errors.required || (control.errors.min && control.value == 0)">
<small style="color: #c62828;">
Value is required.
</small>
</div>
</ng-container>
</div>
Currently, my goal is to utilize this component within another html file by using the code below:
<form [formGroup]="profileActivityForm">
<app-select [control]="profileActivityForm.get('activityType')" [idAndForAttributes]="'type'" [label]="'Type'"
[options]="profileActivityTypes"></app-select>
</form>
In the corresponding Typescript file (TS), I have:
profileActivityTypes: string[] = [];
ngOnInit() {
this.profileActivityTypes.push('New')
this.profileActivityTypes.push('Update')
this.profileActivityForm = this.fb.group({
activityType: [0]
});
}
However, there seems to be an issue where invisible options are being displayed as shown in this picture.
I suspect the problem lies within the HTML code of the reusable component:
<option *ngFor="let item of options" [ngValue]="item.id">{{item.description}}</option>
The error might occur due to it trying to display a description. How can I send the items as descriptions from the child component?
UPDATE
I attempted:
profileActivityTypes: [] = [];
....
let profileActivities = [{ description: 'New' }, { description: 'Update' }]
this.profileActivityTypes.push(profileActivities)
Nevertheless, it throws an error upon pushing:
Argument of type '{ description: string; }[]' is not assignable to parameter of type 'never'