代码之家  ›  专栏  ›  技术社区  ›  HDJEMAI

正确的方法初始化被动窗体的输入字段并使控件有效

  •  0
  • HDJEMAI  · 技术社区  · 6 年前

    这里的问题应该很简单,但我无法初始化一个被动窗体的输入字段,并使该控件有效。

    @Component({
      selector: 'app-profile-editor',
      templateUrl: './profile-editor.component.html',
      styleUrls: ['./profile-editor.component.css']
    })
    export class ProfileEditorComponent {
      profileForm = this.fb.group({
        firstName: string,
        lastName: string,
    
        address: this.fb.group({
          fName: ['initial value', [Validators.required]],
          city: ['', [Validators.required]],
          state: [''],
          zip: ['']
        }),
      });
    
      constructor(private fb: FormBuilder) { }
    }
    

    在模板中我可以说:

    <input [(ngModel)]="firstName" formControlName="fName" />
    

    fName: ['initial value', [Validators.required]],
    

    第二种方法不起作用:

    fName: new FormControl('initial value', [Validators.required])
    

    第三种方法是 在模板中,这样做不起作用:

     <div>
        <input [(ngModel)]="firstName" formControlName="fName" [value]="'default value'"/>
     </div>
    

    第四种方法是:

    this.address.controls['fName'].setvalue('default value');
    this.address.controls['fName'].updateValueAndValidity();
    

    因此,即使在我的表单中,该字段最初已填充,并且我必须提供其他字段,但由于该字段,我的表单无效,因此它不会将我的保存按钮显示为已启用。

    有人能解释为什么会有这样的行为,或者解释什么是正确的方法吗?

    我必须清理这个例子,但这里有一个使用: <input type=“text”class=“表单控件”

    https://stackblitz.com/edit/angular-reactive-forms-jhg6ds?file=app%2Fapp.component.ts

    (稍后将更新此示例。)

    1 回复  |  直到 4 年前
        1
  •  1
  •   HDJEMAI    4 年前

    编辑版本: https://stackblitz.com/edit/angular-reactive-forms-atvaym

    模板:

    <form [formGroup]="SignupForm" (ngSubmit)="onSubmit()">
        <div class="form-group">
            <label for="username">UserName</label>
            <input type="text" class="form-control" id="username" formControlName="username">
            <span class="help-block" *ngIf="!SignupForm.controls.username.valid && SignupForm['controls'].username.touched">
       <span *ngIf="SignupForm['controls'].username.hasError('nameIsForbidden')">name is invalid</span>
            <span *ngIf="SignupForm['controls'].username.hasError('required')">field is required</span>
            </span>
        </div>
    
        <div class="form-group">
            <label for="email">Email</label>
            <input type="email" class="form-control" id="email" formControlName="email">
            <span class="help-block" *ngIf="!SignupForm.controls.email.valid && SignupForm['controls'].email.touched">
       <span *ngIf="SignupForm['controls'].email.hasError('emailIsForbidden')">name is invalid</span>
            <span *ngIf="SignupForm['controls'].email.hasError('required')">field is required</span>
            </span>
        </div>
    
        <div class="radio" *ngFor="let gender of genders">
            <label>
    <input type="radio" [value]="gender" formControlName = "gender">{{gender}}
    </label>
        </div>
    
        <div formArrayName="hobbies">
            <h4>Hobbies</h4>
            <button class="btn btn-default" type="button" (click)="onAddHobby()">Add Hobby</button>
            <div class="form-group" *ngFor="let hobbyControl of SignupForm['controls'].hobbies['controls']; let i=index">
                <div [formGroupName]="i">
                    <div [formGroup]="SignupForm['controls'].hobbies['controls'][i]">
                        <input type="text" class="form-control" formControlName="name">
                    </div>
                </div>
            </div>
        </div>
        <span class="help-block" *ngIf="!SignupForm.valid && SignupForm.touched">please enter valid data</span>
        <button class="btn btn-primary" type="submit">Submit</button>
    </form>
    

      ngOnInit(){
        this.SignupForm = this.fb.group({
          username: [{value: 'default name', disabled: false}, [Validators.required, this.validateName()]],
          email: [{value: 'default name', disabled: false}, [Validators.required, Validators.email, this.validateEmail()]],
          gender: [{value: 'female', disabled: false}, [Validators.required]],
          hobbies: this.fb.array([])
        });
      }
    
      onAddHobby(){
        const controls = <FormArray>this.SignupForm.controls['hobbies'];
        let control = this.fb.group({
          name: [{value: 'hobbi', disabled: false}]
        });
        
        controls.push(control);
      }
    
      private validateName(): ValidatorFn {
        return (control: AbstractControl): {[key: string]: any} => {
          for(let i of this.forbiddenUserNames){
            if(i === control.value){
              return {'nameIsForbidden': true};
            } else {
              return null;
            }
          }
        }
      }
        
      private validateEmail(): ValidatorFn {
        return (control: AbstractControl): {[key: string]: any} => {
          if(control.value === 'test@test.com'){
            return {'emailIsForbidden': true};
          } else {
            return null;
          }
        }
      }
    

    我建议看一下这篇关于异步验证器的文章 https://alligator.io/angular/async-validators/