2016-12-22 59 views
1

我想在angular2中使用#variable =「ngForm」。我如何在formControl輸入中使用它? Angular的每個版本都有很多變化,我無法使用#variable,而不是使用「feedbackForm.controls.personalData.controls.firstName」,這對磁帶來說太長了。不知道是否有其他方式來做到這一點。謝謝。如何在模型驅動表單中使用#variable(NgForm輸入指令)?

<form [formGroup]="feedbackForm" novalidate (ngSubmit)="onSubmit(this.feedbackForm)"> 
     <div formGroupName="personalData"> 
      <div class="form-group"> 
       <label for="firstName">First name</label> 
       <input formControlName="firstName" id="firstName" type="text" class="form-control" required /> 
       <div class="alert-info alert-danger" 
        *ngIf="feedbackForm.controls.personalData.controls.firstName.touched && feedbackForm.controls.personalData.controls.firstName.errors">FirstName is required</div> 

     </div> 
... 
... 
... 

********** **********構造

constructor(@Inject(FormBuilder) fb: FormBuilder) { 


this.feedbackGroup = fb.group({ 
     comment: ['', Validators.required] 
    }); 

    this.feedbackForm = fb.group({ 
     personalData: fb.group({ 
      firstName: [``, Validators.required], 
      lastName: [``, Validators.compose([Validators.required, CustomerValidators.cannotContainSpace]), CustomerValidators.shouldBeUnique], 
      phoneNumber: [] 
     }), 
     feedback: this.feedbackGroup 
    }); 
} 
+0

你也可以用'personalData.get( '的firstName')做內部touched' – ranakrunal9

+0

檢查https://toddmotto.com/angular-2-forms-template-driven – ranakrunal9

回答

0

一般來說,你應該結構和模型和模板驅動形式相匹配。 我建議什麼:

<form [formGroup]="feedbackForm" novalidate (ngSubmit)="onSubmit(this.feedbackForm)"> 
     <div [formGroup]="personalData"> 
      <div class="form-group"> 
       <label for="firstName">First name</label> 
       <input [formControl]="firstName" id="firstName" type="text" class="form-control" required /> 
       <div class="alert-info alert-danger" 
        *ngIf="firstName.touched && firstName.errors">FirstName is required</div> 

     </div> 

export class thatComponent { 
    private firstName:FormControl; 
    private personalData:FormGroup; 
    private feedbackForm:FormGroup; 
    constructor(){ 
     this.feedbackForm = .... // what ever you've done 

     this.personalData = this.feedbackForm.get(['personalData']) 
     this.firstName = this.personalData.get(['firstName']) 

    } 

} 
+0

如何在更新後的構造函數中進行修改(在頂部文章中)? – amin89

+0

謝謝你的工作;) – amin89

+0

正確答案: this.feedbackForm.get(「personalData.firstName」)將一個屬性存取到PersonalData – amin89

相關問題