FormGroup中的Angular 2/4 FormControl无法在带有标签的表单上显示

时间:2017-08-23 09:23:44

标签: javascript angular angular-reactive-forms angular-forms

我不明白该怎么做

  1. 特定值的console.log
  2. 显示在HTML页面上的标签中
  3. 以输入文字显示
  4. 这是我的Component Typescript和新的FormGroup,然后是新的FormControls

        this.trackerForm = new FormGroup({
            session: new FormControl('', Validators.required),
            date: new FormControl(new Date(), [
                Validators.required
            ]),
            contactType: new FormControl('', [
                Validators.required
            ]),
            customerType: new FormControl('', Validators.required),
            firstName: new FormControl('', [Validators.required, Validators.minLength(80)]),
            lastName: new FormControl('', [Validators.required, Validators.minLength(80)]),
            phone: new FormControl('', [Validators.required, Validators.maxLength(10), Validators.minLength(10)]),
            extension: new FormControl('', [Validators.maxLength(7)])
    
        });
    
        // this outputs the entire json
        console.log(JSON.stringify(this.trackerForm.value));
        //How do I ONLY console.log  one of the values?   date?
    
    页面上的

    HTML -

    <form [formGroup]="trackerForm" (ngSubmit)="onSubmit(trackerForm.value)" novalidate>
    
     <div>
          <label class="form-control"><span>{{trackerForm.date.value}}  </span></label>
        </div>
    

2 个答案:

答案 0 :(得分:6)

<form [formGroup]="trackerForm" (ngSubmit)="onSubmit(trackerForm.value)" novalidate>

 <div>
      <label class="form-control"><span>{{trackerForm.get('date').value}}  </span></label>
    </div>

<label class="form-control"><span>{{trackerForm.controls['date'].value}}  </span></label>

但第一个肯定更好,因为'AOT'不编译第二个。

但我会创建一个组件getter以使其更好:

 get dateControl(){
     return this.trackerForm.get('date');
 }

然后:

    <form [formGroup]="trackerForm" (ngSubmit)="onSubmit(trackerForm.value)" novalidate>

 <div>
      <label class="form-control"><span>{{dateControl.value}}  </span></label>
    </div>

答案 1 :(得分:0)

您需要通过formGroup对象访问trackerForm.controls控件。

"date"控制值trackerForm.controls['date'].value的示例。