2017-10-20 52 views
0

我已經創建了下面的角度分量控制檯:角提交投手不將數據記錄到

import { Component } from '@angular/core'; 
import { FormGroup } from '@angular/forms'; 

@Component({ 
    selector: 'weather-search', 
    template: ` 
     <section> 
      <form (ngSubmit)="onSubmit(f)" let f="ngForm" class="search__form"> 
       <label for="search_city">Enter City</label> 
       <input ngControl="location" type="text" id="search_city" placeholder="Enter City" required/> 
       <button type="submit">Add City</button> 
      </form> 
      <div class="locationsearch__info"> 
       <span class="info">City Found</span>:<span>Kansas</span> 
      </div> 
     </section> 
    `, 
    styleUrls: ['./weather-search.component.css'] 
}) 


export class WeatherSearchComponent { 
    onSubmit(form: FormGroup) { 
     console.log(form); 
    } 
} 

我使用這個組件在我app.component.ts像這樣:

@Component({ 
    selector: 'app-root', 
    template: ` 
    <weather-search></weather-search> 
    <weather-list></weather-list> 
    `, 
    styleUrls: ['app.component.css'] 
}) 

現在事情是當我點擊提交我期望提交將被停止,並且表單數據將被console.log'ed,這不是什麼現在正在發生,只是爲了簡要預覽我的代碼,注意我有一個局部變量let f="ngForm"並提交我傳遞這個變量提交處理器像這樣(ngSubmit)="onSubmit(f)"

截至目前爲止,雖然在提交我看不到在控制檯。爲什麼我的提交處理程序不工作?

回答

2

你必須使用#符號在你的情況來定義這樣一個局部變量:

<form (ngSubmit)="onSubmit(f)" #f="ngForm" class="search__form"> 
1

嘗試這樣的:

模板:

<form name="f" (ngSubmit)="onSubmit(f)" #f="ngForm" class="search__form"></form> 

打字稿:

import { NgForm } from '@angular/forms'; 

export class HomeComponent { 
    onSubmit(f: NgForm) { 
     console.log('f', f); 
    } 
}