ngModel在Angular4中不起作用

时间:2017-06-28 05:02:44

标签: angular ngmodel

我正在从official site学习Angular 4,我来到了2-way data binding through ngModel的部分。但是,一旦我将[(ngModel)]添加到我的组件模板,我的应用程序就会停止工作,即使在module.ts文件中导入了FormsModule。组件无法加载 我正在使用Visual Studio Code 这是我的app.component.ts

   import UIKit
    import Foundation
    import SDWebImage

    class TableViewController: UITableViewController,UISearchBarDelegate,UISearchResultsUpdating {
        //var sections = ["recent","old"]
        var TableData:Array<String> = Array <String>()
        //var TableDataRecent:Array<String> = Array <String>()
        var TableImage:Array<String> = Array <String>()
        var appoid:Array<String> = Array <String>()


        var filteredArray:[String]=[]
        var filteredImage:[String]=[]
        let searchController = UISearchController(searchResultsController:nil)


        override func viewDidLoad() {
            super.viewDidLoad()
            getData()
            self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cells")
            searchController.searchResultsUpdater = self
            searchController.dimsBackgroundDuringPresentation=false
            definesPresentationContext=true
            self.tableView.tableHeaderView = searchController.searchBar
            // Do any additional setup after loading the view, typically from a nib.
            tableView.reloadData()
        }

        override func didReceiveMemoryWarning() {
            super.didReceiveMemoryWarning()
            // Dispose of any resources that can be recreated.
        }
        //
        //    override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        //
        //        return sections[section]
        //
        //    }
        //
        //    override func numberOfSections(in tableView: UITableView) -> Int {
        //        // #warning Incomplete implementation, return the number of sections
        //
        //        return sections.count
        //
        //    }



        override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            if searchController.isActive && !searchController.searchBar.isEqual("") {
                return self.filteredArray.count
            }
            else{
                return TableData.count
            }
        }

        override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            //here cells is the identifier name of prototype cell

            let cell = self.tableView.dequeueReusableCell(withIdentifier: "cells", for: indexPath)

            if searchController.isActive && !searchController.searchBar.isEqual(""){
                cell.textLabel?.text = filteredArray[indexPath.row]
                //cell.imageView?.image = filteredImage[indexPath.row]
    //            print("filteredimage")
    //            print(filteredImage)
    //            print(indexPath.row)
                cell.imageView?.sd_setImage(with: URL(string: TableImage[indexPath.row]), placeholderImage: UIImage(named: "PA"))
                print(TableData[indexPath.row])

                print(appoid[indexPath.row])
            }
            else{
                cell.textLabel?.text = self.TableData[indexPath.row]
                //cell.imageView?.image = self.TableImage[indexPath.row]
                cell.imageView?.sd_setImage(with: URL(string: TableImage[indexPath.row]), placeholderImage: UIImage(named: "PA"))
            //cell.= appoid[indexPath.row]

            }


        return cell
    }





    func filterContentForSearch(searchString:String){
        self.filteredArray=self.TableData.filter(){nil != $0.range(of:searchString)}
     self.filteredImage=self.TableImage.filter(){nil != $0.range(of:searchString)}

        self.tableView.reloadData()
    }


    func updateSearchResults(for searchController: UISearchController) {
        self.filterContentForSearch(searchString: searchController.searchBar.text!)
    }




    func getData() {


        var request = URLRequest(url: URL(string: "*********")!)
        //request.httpMethod = "POST"
        //let postString = "date="+x
        //request.httpBody = postString.data(using: .utf8)
        //print(request.httpBody)
        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            guard let data = data, error == nil else {                                                 // check for fundamental networking error
                print("error=\(error)")
                return
            }

            if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {           // check for http errors
                print("statusCode should be 200, but is \(httpStatus.statusCode)")
                print("response = \(response)")
            }

            let responseString = String(data: data, encoding: .utf8)
            print("responseString = \(responseString)")

            do{

                let json = try JSONSerialization.jsonObject(with: data, options:.allowFragments) as! [String:AnyObject]

                if let stations = json["result"] as? [[String: AnyObject]] {
                    for station in stations {
                        let name = station["patient_name"] as! String
                        //self.login = login_value
                        let profile_pic = station["image"] as! String
                        let status = station["status"] as! String

                        let appo_id = station["id"] as! String
                    //    let appo_id = station["appointment_id"] as! String
                        //let status = station["status"] as! String
                        //let appo_time = station["appointment_time"] as! String
                        //let appo_duration = station["time_duration"] as! String
                        //let reason = station["reason"] as! String
                        print(name,status)

                        self.TableData.append(name)
                        self.TableImage.append(profile_pic)
                        self.appoid.append(appo_id)

                    }







                    print(self.TableData)
                    print(self.TableImage)
                    //print(self.items)
                    //self.do_table_refresh();
                    self.tableView.reloadData()

                }

            }catch {
                print("Error with Json: \(error)")
            }



        }
        task.resume()



    }






}

这是app.module.ts

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

    export class Hero {
      id: number;
      name: string;
    }



    @Component({
      selector: 'app',
      template: `
      <h1>{{ title }}</h1>
      <h2>{{hero.name}} details!</h2>
      <div><label>Id:</label> {{hero.id}} </div>
      <div>name:<input [(ngModel)]="hero.name" type="text"></div>
      `,
      styles:[`
        .selected{
          transition: padding 0.3s;
          color: mediumseagreen;
        }
      `]
    })

    export class AppComponent {
      title = 'Tour Of Heroes';

     hero:Hero = {
       id:1,
       name:"Mr. Invisible"
     };
    }  

AppComponent未加载,只显示

加载...

6 个答案:

答案 0 :(得分:18)

import { FormsModule } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

    import { AppComponent, Hero } from './app.component';

    @NgModule({
      declarations: [
        AppComponent

      ],
      imports: [
        BrowserModule,
        FormsModule  // forms module should be in imports not in declarations
      ],
      providers: [],
      bootstrap: [AppComponent]
    })
    export class AppModule { } 

答案 1 :(得分:3)

// add the import in module and add FormModule in import:
import { NgModule } from '@angular/core'
 imports: [
    BrowserModule,
   // add FormModule in import
    FormsModule
]

答案 2 :(得分:3)

正如其他人指出的那样,导入FormsModule(例如,在您的app.module.ts文件中。)是很重要的。在这个特定的问题中,导入部分中缺少它。

但是我添加了这个答案,以警告您其他不时发生的事情。

如果您仅使用ngModel独立但没有任何形式的表单,则不必为输入指定name

<input ... [(ngModel)]="model.something"`>

但是当您以某种形式使用它时,name属性将成为必填项!

<form>
  <input ... name="something" [(ngModel)]="model.something"`>
</form>

它实际上在文档中:

在标记中使用ngModel时,还需要提供一个name属性,以便可以使用该名称在父表单中注册控件。

如果您错过它,它将根本不会显示任何错误,它将无法正常工作。

答案 3 :(得分:2)

除了模块声明的FormsModule部分中需要imports之外,您还必须使用form标记或ngForm指令来启用{{ 1}}功能。

没有你也可以使用独立控件来使用ngModel,如下所示:

ngModel

来源:Angular documentation

答案 4 :(得分:0)

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

然后在@NgModule(){imports:[FormsModule]}与其他工作人员

答案 5 :(得分:0)

双向绑定

在 app.module.ts 内

从'@angular/forms'导入{FormsModule};

进口:[ 表单模块 ],