Ich habe eine sehr einfache Form, bestehend aus einem Eingabefeld und einer Schaltfläche. Ich versuche, Angular2-Validatoren verwenden, um eine Fehlermeldung anzuzeigen, wenn alles andere als Zahlen in das Eingabefeld eingegeben werden, und auch die Übermittlungsschaltfläche zu deaktivieren, wenn das Eingabefeld ungültig oder leer ist. Aus irgendeinem Grund wird die Fehlermeldung angezeigt, egal was eingegeben wird ... Irgendeine Idee, was ich falsch mache?sehr einfache angular2 Form wird nicht validiert
mein Code:
app.component.html:
<div class="row">
<div class="col-md-4 col-md-push-4">
<form [formGroup]="barcodeForm" role="form" (ngSubmit)="submitBarcode(barcode)" >
<div class="form-group">
<input type="number" class="form-control" id="barcode" placeholder="Enter Barcode" [formControl]="barcodeForm.controls['barcode']" [(ngModel)]="barcode" name="barcode" #focusInput>
<div [hidden]="barcode.valid || barcode.pristine" class="alert alert-danger">A barcode can only consist of numbers (0-9)...</div>
</div>
<button class="btn btn-submit btn-block" [disabled]="!(barcode.valid) || barcode.pristine">Submit</button>
</form>
</div>
</div>
Teil app.component.ts:
import { Component, ViewChild, ElementRef, AfterViewInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { RestService } from "./services/rest.service";
import { ProductModel } from "./models/product.model";
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements AfterViewInit {
@ViewChild('focusInput') focusInput: ElementRef;
barcode: string;
barcodeForm: FormGroup;
product: ProductModel;
constructor(fb: FormBuilder, private restService: RestService){
this.barcodeForm = fb.group({
'barcode':['', [Validators.required, Validators.pattern("[0-9]+")]]
});
}
Wie kann ich den Barcode-Wert ohne das ngModel erhalten? Ich habe kein Barcode-Modell, da es nur ein Barcode ist: string ... – user2094257
Verwenden Sie Folgendes: '(ngSubmit) =" submitBarcode (barcodeForm.value.barcode) "' – Amit
Vielen Dank @Amit Dahan – user2094257