Angular4:使用@ViewChild() 意外刷新应用程序

Angular4: unexpected app refresh with @ViewChild()

我正在尝试通过@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"

更改以下行:

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

至:

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

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

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

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

在 angular 世界中,您应该在 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>