2016-07-26 79 views
3

我正在嘗試使用Angular 2 Forms進行驗證,但是當我嘗試添加多個控件時。它似乎只是被忽略。我遵循了許多不同的指南來看看其他人是如何做到這一點的,但這些方法似乎都沒有奏效。Angular 2 Form「找不到控件」

我一直在做的是這在我的模板:

<form [formGroup]="form" novalidate (ngSubmit)="save(form.valid)"> 
<div class="row" id="message-wrapper"> 
    <label>Message</label> 
    <small [hidden]="form.controls.message.valid || (form.controls.message.pristine && !submitted)"> 
     Message is required (minimum 10 characters). 
    </small> 
    <textarea 
     class="textarea-scaled" 
     type="text" 
     [(ngModel)]="campaign.message" 
     formControlName="message" 
     placeholder="This will be sent out by supporters with a URL back to this campaign"> 
    </textarea> 
</div> 

<div class="row" id="promo-wrapper"> 
    <label>Promotion: </label> 
    <small [hidden]="form.controls.promotion.valid ||(form.controls.promotion.pristine && !submitted)"> 
     Promotion is required and should be between 10 and 100 characters 
    </small> 
    <textarea 
     class="textarea-scaled" 
     type="text" 
     [(ngModel)]="campaign.promotion" 
     formControlName="promotion" 
     placeholder="What would you like to be sent out in promotional messages?"> 
    </textarea> 
</div> 
</form> 

然後在我的部分我這樣做:

form: FormGroup; 

    constructor(private builder: FormBuilder, 
       private _dataservice: DataService) { 

     this.form = builder.group({ 
      "message": ['', [Validators.required, Validators.minLength(10)]], 
      "promotion": ['', [Validators.required, Validators.minLength(10)]] 
     }); 
    } 

但我不斷收到「無法找到控制‘促銷’」控制檯錯誤...

任何幫助將不勝感激!

+0

您是否已將REACTIVE_FORM_DIRECTIVES元素添加到組件? – micronyks

+0

是的,這是在我的指令。對不起,我沒有表現出來。 –

+0

你可以請求重生嗎? – micronyks

回答

4

這可能不是原問題的答案,但如果您從Google跳到此處,這可能會有用。

你需要檢查這些東西。

  1. 您必須爲具有[ngModel]

  2. 如果排除驗證某些領域的所有控制一個「name」屬性,然後添加[ngModelOptions]="{standalone: true}"(記住第一條規則,你仍然需要一個「名「)

  3. 確保您具有要驗證的控件的formControlName屬性。 (請記住第一條規則)

+0

是不是這樣,但我得到了錯誤,因爲我忘記在FormGroup初始化中聲明**鍵** ... – manatico

+0

如果您有'formControlName',則不需要'name' attr。 –

1

我試着在我的組件中創建新的FormGroup。 我已經從angular/forms中導入了ReactiveFormsModule,並將其添加到了app.module.ts中。

,但我得到找不到名稱「FormGroup」找不到名稱「FormControl」錯誤

這裏是我的組件

export class SignupFormComponent { 
    form1 = new FormGroup({ 
    username: new FormControl(), 
    password: new FormControl() 
    }); 
} 

添加的成分以下import語句解決了我問題。

import { FormGroup, FormControl } from '@angular/forms'; 

不是你的問題的答案,而是發佈,因爲這可能會幫助面臨同樣錯誤的人。