带有数据绑定的Input元素的Angular 4指令

时间:2018-01-10 17:43:41

标签: angular angular-directive angular4-forms

我试图在我的表单中为输入元素编写属性指令,如果它可用或不可用,则验证给定的用户名。

我有两个问题。

1)我想通过允许它接收应该验证用户名的API路由来使该指令可重用。这就是我所拥有的,因为你可以看到它不接受任何输入(没有绑定)并且它完美地工作。

import { Directive, forwardRef } from '@angular/core';
import { AbstractControl, Validator, NG_ASYNC_VALIDATORS } from '@angular/forms';
import { HttpClient } from '@angular/common/http';
import { environment } from '../../../../environments/environment';
import { Observable } from 'rxjs/Observable';

@Directive({
  selector: '[uniqueCompanyUsername]',
  providers: [
    {
      provide: NG_ASYNC_VALIDATORS,
      useExisting: forwardRef(() => CompanyUsernameValidatorDirective), multi: true
    },
  ]
})
export class CompanyUsernameValidatorDirective implements Validator {
  constructor(private http: HttpClient) {
  }

  validate(username: AbstractControl) {
    return Observable.timer(1000).switchMap(() => {
      return this.http.post(environment.apiEndpoint + '/company/username-check', {
        username: username.value
      }).map((result: any) => result.success ? null : { uniqueCompanyUsername: false });
    });
  }
}

一旦我向它添加@Input('uniqueCompanyUsername') route: string;并尝试通过指令本身获取路线,它就会给我这个错误:

  

无法绑定到" uniqueCompanyUsername'因为它不是一个已知的属性   '输入'

这是我在指令控制器中写的内容:

import { Directive, forwardRef, Input } from '@angular/core';
import { AbstractControl, Validator, NG_ASYNC_VALIDATORS } from '@angular/forms';
import { HttpClient } from '@angular/common/http';
import { environment } from '../../../../environments/environment';
import { Observable } from 'rxjs/Observable';

@Directive({
  selector: '[uniqueCompanyUsername]',
  providers: [
    {
      provide: NG_ASYNC_VALIDATORS,
      useExisting: forwardRef(() => CompanyUsernameValidatorDirective), multi: true
    },
  ]
})
export class CompanyUsernameValidatorDirective implements Validator {
  constructor(private http: HttpClient) {
  }

  @Input('uniqueCompanyUsername') route: string;

  validate(username: AbstractControl) {
    return Observable.timer(1000).switchMap(() => {
      return this.http.post(`${environment.apiEndpoint}${this.route}`, {
        username: username.value
      }).map((result: any) => result.success ? null : { uniqueCompanyUsername: false });
    });
  }
}

这是我的模板:

<input name="companyUsername" [(ngModel)]="company.username" id="input-username" #companyUsername="ngModel" class="form-control" placeholder="Company Username"
                [class.form-control-danger]="companyUsername.invalid && companyUsername.touched" [minlength]="3" [maxlength]="50" [required]="true"
                [uniqueCompanyUsername]="/company/username/" autofocus>

我很沮丧,我不能简单地理解这里的错误!

1 个答案:

答案 0 :(得分:1)

您的属性名称需要与您的输入装饰器名称匹配。

改变这个:

@Input('uniqueCompanyUsername') route: string;

到此:

@Input() uniqueCompanyUsername: string;

并记得将组件中的“this.route”更改为“this.uniqueCompanyUsername”。

有关Avoid aliasing inputs and outputs.

的更多信息