反应式表单。'blur'

问题描述 投票:0回答:2

我有一个简单的文本输入,在我的web应用程序前端Angular,需要一个用户名。

<div [formGroup]="userNameFormGroupEnquiry">    
<mat-form-field>
      <mat-label>Chosen Name:</mat-label>
      <input name="chosenName" formControlName="chosenName" [(ngModel)]="chosenName" matInput type="text" placeholder="JOHN DOE"/>
      <mat-hint align="end">REQUIRED FIELD!</mat-hint>
      <mat-error *ngIf="hasNameError('chosenName', 'required')"
        >Minimum and Maxmimum of length 12 is required!</mat-error
      >
    </mat-form-field>
</div>

我使用formGroup是因为我打算在这个div中添加更多的输入字段,只是想先让这个输入工作。

我使用了 [(ngModel)]="chosenName"来捕捉输入值,并将其赋值给我的Component类中的一个变量(this.chosenName).

下面是我的组件。

@Component({
  selector: 'app-user',
  templateUrl: './userInput.component.html',
  styleUrls: ['./userInput.component.scss']
})
export class UserInputEnquiry implements OnInit {
  title = 'Welcome to this note-taking app!';
  chosenName: string;
  enquiryByUserInputForm: FormGroup;

  constructor() {}

  ngOnInit() {
    this.enquiryByUserInputForm = new FormGroup({
      chosenName: new FormControl('', [Validators.required, Validators.minLength(9), Validators.maxLength(9)])
    });
  }

  public hasLengthError = (controlName: string, errorName: string) => {
    return this.enquiryByUserInputForm.controls[controlName].hasError(errorName);
  };

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

}

根据我之前问题的回答,我被告知不要使用 [(ngModel)] 因为FormControl已经包含了Input capturing,我得到了一个非常严重的警告,但是怎么会这样?

如果我删除 [(ngModel)]="chosenName" 的输入,输入永远不会被捕捉到。this.chosenName 而控制台记录了一个空白的undefined输出。我是不是遗漏了什么?

angular angular-reactive-forms angular-validation form-control
2个回答
1
投票

如果你想要任何初始值,那么初始化 chosenName 与此。

chosenName: string = '';

然后你就可以用这个值来初始化表单。

this.enquiryByUserInputForm = new FormGroup({
  chosenName: new FormControl(this.chosenName, [Validators.required, Validators.minLength(9), Validators.maxLength(9)])
});

在提交时,你可以用这个值访问所有的表单值。

  onSubmit() {
      console.log(this.enquiryByUserInputForm.value);
  }

要获得一个特定的控件值,你可以这样做:

  onSubmit() {
      console.log(this.enquiryByUserInputForm.get('chosenName').value);
  }

EDIT:chosenName 类属性可以完全省略,因为它只是起到了初始化的作用,这一点你可以在创建表单时直接完成。


0
投票

如果你使用的是ReactiveFormsModule,你可以订阅值的变化。

this.userNameFormGroupEnquiry.valueChanges.subscribe(values => do something)

values将是一个对象,其中{ formcontrolname: valueofinput}。

每当任何一个输入发生变化时,就会发射,太频繁了。所以你可以做一些事情来控制事情。

this.userNameFormGroupEnquiry.valueChanges.pipe(
     filter(() => this.userNameFormGroupEnquiry.valid && 
                  this.userNameFormGroupEnquiry.dirty),
     debounceTime(1000))
    .subscribe(values => do something)

这将检查表单的变化和有效性,并debounces;意味着它将在最后一次击键后一秒发出。这还是经常发生火灾,还有一件事你可以做。

当你定义表单控件时,你可以做这样的事情。

this.userNameFormGroupEnquiry = new FormGroup( {
    chosenName: new FormControl('', { updateOn: 'blur', validators: 
              Validators.required }),
    ...
    })

updateOn可以设置为 "改变

© www.soinside.com 2019 - 2024. All rights reserved.