如何使用角度2中的反应形式启用按钮?

时间:2017-09-19 12:30:12

标签: angular typescript primeng

我有一个输入字段和一个按钮。当字段不为空时,按钮应该被启用。但在我的情况下我已经传递了输入值。所以它应该被启用但是这不会发生。它正在当我在输入字段中输入任何内容时启用。有关如何实现它的任何信息。下面是我的代码

export class SignupFormComponent implements OnInit {
  userForm: FormGroup;
  submitted: boolean;
  hello = "hello world";

  ngOnInit() {
    this.userForm = new FormGroup({
      firstName: new FormControl('',[<any>Validators.required, <any>Validators.minLength(5)])
    });
  }

  onSubmit({ value, valid }: { value: userForm, valid: boolean }) {
    this.submitted = true;
    console.log(value,valid);
  }
}

这是我的HTML代码

<form [formGroup]="userForm" (ngSubmit)="onSubmit(userForm)" validate>
  <div class="form-group">
    <label>First Name</label>
    <input type="text" class="form-control" formControlName="firstName" [value]="hello">
  </div>
  <button type="submit"  class="btn btn-primary" [disabled]="userForm.invalid">Submit </button>
</form>

2 个答案:

答案 0 :(得分:3)

从您的输入中删除 [value] =&#34; hello&#34; ,因为它们应该放在new FormControl(value, [validators], [asyncValidators])中以获取被动表单。

类似的东西:

ngOnInit() {
  this.userForm = new FormGroup({
    firstName: new FormControl(this.hello, [<any>Validators.required, <any>Validators.minLength(5)])
  });
}

答案 1 :(得分:0)

简单的方法是使用反应形式,如下所示:

  • step1:导入ReactiveForm,FormBuilder,Validators
  • step2:声明FormGroup对象并将表单构建器注入构造函数
  • 第3步:初始化您的表单组
  • 步骤4:以与您相同的方式使用反应形式,但进行一些更改

代码:

export class SignupFormComponent implements OnInit {
  userForm: FormGroup;
  firstName: string;

  constructor(private _formBuilder:FormBuilder){}

  ngOnInit() {
    this.userForm = this._formBuilder.group({
      'firstName': ['',[Validators.required,Validators.minLength(5)]]
    });
  }

  onSubmit() {
    console.log(this.firstName);
  }
}

HTML:

 <form [formGroup]="userForm" (ngSubmit)="onSubmit()" name="userForm">
      <div class="form-group">
        <label>First Name</label>
        <input type="text" [(ngModel)]="firstName" class="form-control" formControlName="firstName">
        <p *ngIf="userForm.controls.firstName.invalid && (userForm.controls.firstName.dirty || userForm.controls.firstName.touched)"> Error message </p>
      </div>
      <button type="submit"  class="btn btn-primary" [disabled]="userForm.invalid">Submit </button>
    </form>