2017-02-18 42 views
2

我正在處理我的聯繫信息,我需要添加到我的firebase數據庫。Angular 2表單驗證沒有給出任何錯誤

我一直在閱讀和關於表單驗證的教程,我認爲我做的都是正確的,但它不以任何方式工作。

我沒有收到任何錯誤。

我需要幫助。

這就是我所擁有的。如果這不是很清楚,請告訴我。

問候,

app.module.ts

import { FormsModule } from '@angular/forms'; 

imports: [ 
    FormsModule, 

contact.component.html

<form > 
    <div class="form-group"> 
    <label for="name">Enter Name</label> 
    <input type="text" class="form-control" id="name" required name="name"[(ngModel)]="name"> 
    <div *ngIf="name.errors && (name.dirty || name.touched) " class="alert alert-danger"> 
     <div [hidden]="!name.errors.required"> 
      Name is required 
     </div> 
    </div> 
    </div> 
    <button class="btn btn-primary" type="submit" name="submit" >Send</button> 
</form> 

這是我的組件

import { Component, OnInit, ElementRef } from '@angular/core'; 
import { Injectable } from '@angular/core'; 
import { AngularFire, FirebaseListObservable } from 'angularfire2'; 
import { Observable } from 'rxjs/Observable'; 
import { Client } from './client'; 
import { FormsModule } from '@angular/forms' 
import 'rxjs/add/operator/map'; 

@Component({ 
    selector: 'app-contact', 
    templateUrl: './contact.component.html', 
    styleUrls: ['./contact.component.css'], 
}) 

export class ContactComponent implements OnInit { 

    clients: FirebaseListObservable<any[]>; 
    name; 

    constructor(af: AngularFire, private elementRef: ElementRef) { 
    this.clients = af.database.list('/clients'); 
    } 

    addItem(){ 
    this.clients.push(this.name); 
    } 

    ngOnInit() { 
    } 

} 

回答

1

對於基於模板的表單驗證,你需要#name="ngModel"

<input type="text" class="form-control" id="name" 
      required 
      [(ngModel)]="model.name" name="name" 
      #name="ngModel"> 

然後,你可以綁定到驗證標誌:

<div [hidden]="name.valid || name.pristine" 
     class="alert alert-danger"> 
     Name is required 
    </div> 
+0

謝謝。我會做,並回復你,讓它知道它是否有效 –

0

您使用的這些角版本?

from angular 4.0。 HTML5驗證已刪除。使其回到

<form NgNoValidate></form>