Home > Blockchain >  Angular - call setters/getters in html
Angular - call setters/getters in html

Time:01-12

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?

CodePudding user response:

try form.getControls['query'].setValue(myValue)

form.get('fieldName') will get value of that field ... form.controls['fieldName'] would get the field itself .. Field control will expose get or set value methods

CodePudding user response:

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(): any {
    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.

  •  Tags:  
  • Related