Angular2 - 表单自定义验证 - 在验证函数外部进行引用()

时间:2016-10-04 15:55:03

标签: angular

我正在为特定的FormControl创建自己的验证,但我无法弄清楚如何引用在验证函数之外定义的外部值。

CODE:

  @Component({
      selector: 'city-autocomplete',
      template: `
     <label for="incidade">Cidade/Comarca:</label>
     <input type="text" class="autocomplete-imput" id="incidade"
      [formControl]=inputcidade
      >
     `,
      styleUrls: ['./city-autocomplete.component.scss']
    })

    export class CityAutocompleteComponent {

    extenalValue :boolean = false



     inputcity = new FormControl('', [this.cityValidator]);

    //My Validator:
      cityValidator(ctrl: AbstractControl) {

        const isValid = this.extenalValue // <== this is UNDEFINED

        return isValid ? null : {
          cityValidator: {
            valid: false
          }
        }
      }
    } 

HTML:

错误:

它显示extenalValue未定义。

正如我所看到的,Abstract Control在@Component之前运行,因此我无法在验证器函数之外定义任何内容。

我的问题:

我应该如何引用此函数之外的值?

感谢。

1 个答案:

答案 0 :(得分:1)

使用函数引用时,对组件类的引用绑定已消失。

有多种方法可以解决这个问题,其中一个选项是:

inputcity = new FormControl('', [this.cityValidator.bind(this)]);

一点注意事项。什么是在组件中执行的验证器功能?