I have in the .ts file the following code:
set query(query: string) {
this.form.get('query').setValue(query);
}
get query() {
return this.form.controls.query;
}
I am trying to call the getter method in .html file as:
<div *ngIf="!query.valid && (query?.dirty || query?.touched)">
<div [hidden]="!query.errors.required">Query is required</div>
</div>
However, an error is thrown. The code works perfectly if I remove the setter from the .ts file.
Why does this happen?
You can do it via two ways,
Way 1:
set query(query: any) {
this.form.get('query').setValue(query);
}
get query() {
return this.form.controls.query;
}
Way 2:
set query(query: string) {
this.form.get('query').setValue(query);
}
get query(): AbstractControl {
return this.form.controls.query;
}
when you assign a value to query
you are assigning it as a string see the incoming argument type in your setter. So by default angular understands it as string type. Then in your HTML, you try to access it as an object which creates a problem for angular as it expects it to be a string but used as an object.