【问题标题】:Angular4: unexpected app refresh with @ViewChild()Angular4:使用@ViewChild() 意外刷新应用程序
【发布时间】: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


【解决方案1】:

当按钮类型在form 内提交时,在表单submit 事件上,它会尝试点击表单级别提供的action(属性)。如果form 上没有操作属性,则刷新页面。要停止这种行为,您可以将按钮 type 更改为 button(仅通过删除 type 属性不会解决问题,隐式按钮具有 submit 类型)。

<button class="btn btn-success" type="button" (click)="addShop()">Add</button>

在角度世界中,您应该在form 级别上使用(ngSumbit)="submit()" 事件,然后您可以将按钮类型保持为submit。幕后表单事件被ngSubmit 事件抑制。您可以从 ngSubmit 事件中指定的函数进行 ajax 调用。

标记

<form (ngSubmit)="addShop()" #heroForm="ngForm">
  <input type="text" id="name" class="form-control">
  <button class="btn btn-success" type="submit">Add</button>
  <p>{{shopName}}</p> 
</form>

【讨论】:

    【解决方案2】:

    去掉按钮中的type="submit",直接替换成type="button"

    更改以下行:

    <button class="btn btn-success" type="submit" (click)="addShop()">Add</button>
    

    到:

    <button class="btn btn-success" type="button" (click)="addShop()">Add</button>
    

    浏览器认为您正在提交表单,这就是它刷新页面的原因

    【讨论】:

      猜你喜欢
      • 2019-03-15
      • 2018-02-17
      • 2018-07-05
      • 1970-01-01
      • 1970-01-01
      • 2023-04-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多