简体   繁体   English

Angular - html 中的调用设置器/获取器

[英]Angular - call setters/getters in html

I have in the.ts file the following code:我在 .ts 文件中有以下代码:

  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:我正在尝试将.html文件中的getter方法称为:

  <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.如果我从 .ts 文件中删除设置器,则代码可以完美运行。

Why does this happen?为什么会这样?

try form.getControls['query'].setValue(myValue)尝试 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 form.get('fieldName') 将获取该字段的值... form.controls['fieldName'] 将获取字段本身.. 字段控件将公开获取或设置值方法

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.当您为query分配一个值时,您将其分配为一个字符串,请参阅您的 setter 中的传入参数类型。 So by default angular understands it as string type.所以默认情况下 angular 将其理解为字符串类型。 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.然后在您的 HTML 中,您尝试以 object 的形式访问它,这会为 angular 造成问题,因为它希望它是一个字符串,但用作 ZA8CFFDEZ8931AC

Although the accepted answer works and the thinking behind it make sense, I would completely avoid using any as a return type, when you know exactly what you're returning.尽管接受的答案有效并且其背后的想法是有道理的,但当您确切知道要返回的内容时,我会完全避免使用any作为返回类型。

That just goes against the purpose of using Typescript as a language.这与使用 Typescript 作为语言的目的背道而驰。 Using any is the same as saying "accept everything and don't just interpret it as a string" .使用any等同于说“接受所有内容,不要仅仅将其解释为字符串”

set query(query: string) {
    this.form.get('query').setValue(query);
}

get query(): AbstractControl {
    return this.form.controls.query;
}

Since you know you're returning an AbstractControl , I would set the return type to either AbstractControl or, if you want to be more specific, to FormControl .既然您知道您要返回AbstractControl ,我会将返回类型设置为AbstractControl ,或者,如果您想更具体一点,设置为FormControl

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM