【发布时间】:2018-02-28 09:05:13
【问题描述】:
我正在尝试通过@ViewChild() 获取输入字段的值。然而,即使它看起来有效,这个方法还是触发了应用程序的意外刷新:
-点击触发事件的按钮后应用会立即刷新
-当使用导航栏浏览应用时,应用会刷新一次
模板:
<input type="text" id="name" class="form-control" #nameInput>
<button class="btn btn-success" type="submit" (click)="addShop()">Add</button>
<p>{{shopName}}</p>
component.ts:
import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
@Component({
selector: 'app-shopping-edit',
templateUrl: './shopping-edit.component.html',
styleUrls: ['./shopping-edit.component.css']
})
export class ShoppingEditComponent implements OnInit {
@ViewChild('nameInput') shopName:ElementRef;
@ViewChild('amountInput') shopAmount:ElementRef;
coucou:string;
addShop(){
this.shopName = this.shopName.nativeElement.value;
}
constructor() { }
ngOnInit() {
}
}
【问题讨论】:
-
去掉按钮中的type="submit",替换成type="button"
-
因为您的按钮类型设置为
submit。另外,为什么要使用ViewChild?从您的代码中可以看出,您只需将元素绑定到ngModel -
这只是为了学习Angular4的练习。我稍后将不得不将此信息传递给其他组件。字符串插值只是检查我是否得到值的快速方法
标签: angular dom data-binding viewchild