angular6雙向綁定

文章參考

angular 常用模塊

如果不引入該模塊,會出現編譯器不報錯,但是瀏覽器不顯示內容的奇怪現象

引入 FormsModule

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

案例

/** * 告訴angular 如何組裝應用 */
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule }   from '@angular/forms';
import { HttpClientModule }   from '@angular/common/http';

import { AppComponent } from './app.component';
import { HeaderComponent } from './page/header/header.component';
import { NewsComponent } from './page/news/news.component';
import {StorageService} from './page/service/storage.service'
import { AppRoutingModule }     from './router/app-routing.module';
import { HttpdemoComponent } from './page/httpdemo/httpdemo.component';

//@NgModule 裝飾器將AppModule標記爲Angular 模塊類(也叫做 NgModule類)
// @NgModule 接收一個元數據對象,告訴Angular 如何編譯和啓動應用
@NgModule({
  // 引入當前項目運行的組件,自定義組件都需要引入並且在這裏聲明
  // 依賴注入
  declarations: [
    AppComponent,
    HeaderComponent,
    NewsComponent,
    HttpdemoComponent
  ],
  // 當前項目依賴哪些模塊
  imports: [
    BrowserModule,
    HttpClientModule,
    // 如果要引入雙向綁定,則需要引入FormModule
    FormsModule,
    AppRoutingModule
  ],
  // 定義服務
  providers: [
    StorageService
  ],
  // 默認啓動哪個組件
  bootstrap: [AppComponent]
})

// 根模塊不需要導出任何東西,因爲其他組件不需要導入根模塊,但是一定要寫
export class AppModule { }
<input type="text" [(ngModel)]="username">
import { Component, OnInit } from '@angular/core';
import {StorageService} from '../service/storage.service';

@Component({
  selector: 'app-news',
  templateUrl: './news.component.html',
  styleUrls: ['./news.component.css']
})
export class NewsComponent implements OnInit {
  public  username: any;

  // 構造方法中添加service類型,就是依賴注入
  constructor(storageService: StorageService) {
    this.username = "username";
  }
  ngOnInit() {
  }

}