use formControlName for custom input component in reactive form

Paridokht picture Paridokht · Sep 10, 2017 · Viewed 8.3k times · Source

There is a custom input component and it is used in a reactive form with validation:

@Component({
    moduleId: module.id.toString(),
    selector: 'custom-select',
    templateUrl: 'custom-select.component.html',
    styleUrls: ['custom-select.component.css']
})
export class CustomSelectComponent {
    @Input() public items: SelectModel[];
    public model: SelectModel;
    constructor(private customSelectService: CustomSelectService) {
        this.customSelectService.Selected.subscribe((data: SelectModel) => {
            this.model = data;
        });
    }
    public newSelect(select: SelectModel): void {
        this.customSelectService.updateSelected(select);
    }
}

which works fine, I am using custom-select in a reactive form and want to validate it like below:

<custom-select id="country" [items]="selectItems" formControlName="country"></custom-select>
<div *ngIf=" myFrom.controls['country'].invalid && (myFrom.controls['country'].dirty 
             || myFrom.controls['country'].touched) " class="ha-control-alert">
    <div *ngIf="myFrom.controls['country'].hasError('required')">Country is required</div>
</div>

this is how I declare the form in component

this.myFrom = this.formBuilder.group({
    country: [null, Validators.required],
})

but when I add formControlName for validations, it gets error which says No value accessor for form control with name: 'country'. How should I handle this?

Answer