Reputation: 1
I use base form controls for input, autocomplete, etc. fields as shown below:
<div *ngSwitchCase="'text'">
<input matInput type="text" formControlName="{{controlName}}"/>
</div>
and now I need to add button to the form as shown below:
<div *ngSwitchCase="'button'">
<button mat-button formControlName="{{controlName}}" (click)="create()">Create</button>
</div>
But I encounter "No value accessor for form control with name: createEmp" error (createEmp
is the controlName
value that I pass from component). So, is it possible to fix this error?
Upvotes: 2
Views: 10832
Reputation: 57939
Fredrick, a button doesn't accept a FormControl, but remember always: a FormControl exists even if there is no "input" in .html. So, you can do, e.g. (imagine you are defining a formGroup called "form")
<button mat-button [disabled]="form.get(controlName).disabled"
(click)="form.get(controlName).setValue("one");
form.get(controlName).markAsTouched()">
Create
</button>
Or, as Kevin Zang said, create a custom FormControl
Upvotes: 4
Reputation: 1072
You need to implement custom reactive form control for your button with implement the ControlValueAccessor interface. See this article for your reference:link
export class TagsComponent implements ControlValueAccessor {
onChange: (value: string[]) => void = () => {};
onTouched: Function = () => {};
isDisabled = false;
…
writeValue(value: string[]) {
this.tags = value || [];
}
registerOnChange(fn: any) {
this.onChange = fn;
}
registerOnTouched(fn: any) {
this.onTouched = fn;
}
setDisabledState(disabled: boolean) {
this.isDisabled = disabled;
}
}
Upvotes: 2