Angular 当我在输入字段中按enter键时,角度重定向
我有以下带有输入字段的应用程序。当我输入并按enter键时,应用程序将转发到Angular 当我在输入字段中按enter键时,角度重定向,angular,typescript,Angular,Typescript,我有以下带有输入字段的应用程序。当我输入并按enter键时,应用程序将转发到http://example.org/?。而不是触发onEnter事件。onKey事件工作正常。如何阻止这种重定向发生 以下是html: <mat-card> <form class="example-form"> <mat-form-field class="example-full-width"> <input matInput placeholder
http://example.org/?
。而不是触发onEnter
事件。onKey事件工作正常。如何阻止这种重定向发生
以下是html:
<mat-card>
<form class="example-form">
<mat-form-field class="example-full-width">
<input matInput placeholder="How can I help" (keyup)="onKey($event)">
<mat-icon matSuffix>?</mat-icon>
</mat-form-field>
</form>
</mat-card>
有时候,奇怪的行为来自我们猜不到的来源。我认为上面提到的所有问题都是正确的,是其他地方的副作用导致了这个问题。检查一下路线守卫之类的东西。。。或者父组件输入处理…我最近遇到了同样的问题,不知道为什么会发生这种情况。为了解决这个问题,我不得不使用Angulars处理表单的方法 我在我的案例中使用了formbuilder:
export class SearchComponent implements OnInit {
name = 'Angular 6';
searchForm: FormGroup;
constructor(private _fb: FormBuilder){ }
ngOnInit(){
this.searchForm = this._fb.group({
'search':['']
});
}
submit(){
console.log(this.searchForm);
}
onKeyup($event){
console.log($event)
}
}
<mat-card>
<form class="example-form" [formGroup]="searchForm" (ngSubmit)="submit()">
<mat-form-field class="example-full-width">
<input matInput placeholder="How can I help" fromControlName="search" (keyup)="onKeyup($event)">
<mat-icon matSuffix>?</mat-icon>
</mat-form-field>
</form>
</mat-card>
导出类SearchComponent实现OnInit{
名称='6';
搜索形式:FormGroup;
构造函数(私有_fb:FormBuilder){}
恩戈尼尼特(){
this.searchForm=this.\u fb.group({
“搜索”:[“”]
});
}
提交(){
console.log(this.searchForm);
}
onKeyup($event){
console.log($event)
}
}
?
您的表单以旧的方式提交,您可以通过添加一个返回false来避免这种情况代码>位于函数末尾
onKey(event) {
console.log(event.target.value)
return false;
}
检查按钮的类型,如果未给出任何类型,则默认情况下采用type=“submit”。这也可能是由于app.module.ts中缺少FormsModule和HttpModule模块造成的
从'@angular/forms'导入{FormsModule};
从'@angular/http'导入{HttpModule};
@NGD模块({
声明:[
应用组件,
],
进口:[
浏览器模块,
FormsModule,//导入FormsModule
HttpModule,//导入HttpModule
],
提供者:[],
引导:[AppComponent]
})
点击enter键时表单正在提交。此行为是默认行为。根据定义,表单是可提交的。有鉴于此,请为表单注册一个提交处理程序,以控制提交表单的含义
@Component({
selector: 'app-search',
templateUrl: './search.component.html',
styleUrls: ['./search.component.css']
})
export class SearchComponent {
onSubmit() {
}
onKey(event) {
console.log(event.target.value)
}
}
现在,在模板中
<form (ngSubmit)="onSubmit()">
<form>
你能提供stackblitz吗?使用@Eliseo NB doSomething函数可以正确启动,但应用程序会直接重定向到/?
路径。除非你重定向,否则不应该发生这种情况。在模板驱动表单和反应式表单之间进行选择与避免意外提交无关。
<form (ngSubmit)="onSubmit()">
<form>