我在Angular 2中编写了一些代码。我有一个简单的表单,当提交表单时,我希望通过表单验证向服务器发送http请求,并将此响应返回给表单中使用的指令。该指令必须检查响应,并在发生错误验证时,将带有错误的数组发送到另一个组件/指令。我不知道如何在onSubmit方法中发送指令。我在我的组件中使用了这个:https://github.com/ghidoz/angular2-form-utils
这是我的表单组件
@Component({
moduleId: module.id,
selector: 'app-form-validator',
templateUrl: 'form-validator.component.html',
styleUrls: ['form-validator.component.css']
})
export class FormValidatorComponent implements OnInit {
@ViewChild(StSubmit) stSubmit:StSubmit;
userForm: FormGroup;
public firstname: string;
public dupa: string = '';
constructor(private formBuilder: FormBuilder,private exampleUserService: StExampleUserRestService) { }
ngOnInit() {
this.userForm = this.formBuilder.group({
'firstname': ['',Validators.required]
});
}
onSubmitc(v){
console.log('V ', v);
console.log('>>>>Form validate component onSubmit');
let userExample = new User(this.userForm.controls['firstname'].value);
this.exampleUserService.post(userExample)
.subscribe(
data => console.log(data),
error => console.log(error)
);
}
ngAfterViewInit() {
}
}
形状component.html
<div class="row">
<p>Form Vertical</p>
<form [formGroup]="userForm" (ngSubmit)="onSubmitc()" st-validate >
<div class="form-group">
<label for="firstname" class="form-control-label">First Name</label>
<input type="text" class="form-control" id="firstname" placeholder="Enter your first name"
formControlName="firstname">
</div>
<input type="submit" value="submit" class="btn btn-primary">
</form>
</div>
我的指令st-validate
@Directive({
selector: '[st-validate]'
})
export class StValidate implements OnInit{
@Input() dupa: string;
form: FormGroupDirective | NgForm;
constructor(private el: ElementRef,
private renderer: Renderer,
@Optional() private formGroup: FormGroupDirective,
@Optional() private ngForm: NgForm) {
this.form = this.formGroup || this.ngForm;
}
ngOnInit(){
this.form.ngSubmit.subscribe((args)=>{console.log('>>>>>>> new event',args)});
this.form.onSubmit = function () {
console.log('St Validate ngsubmit',this.ngSubmit);
//this.ngSubmit.fn(null);
this.ngSubmit.emit(null);
console.log("validate onSubmit()",this.form);
console.log("Dupa",this.dupa);
return false;
};
}
}
我希望我能很好地解释我的问题。