天天看點

Angular2 小貼士 Name

Angular2 正式版已經釋出了一個月了,我也是通過各種方式在進行驗證是否可以滿足我們的需求,今天我就發現了一個問題。現在我們來一起說明一下,這個可能不算是bug,而應該需要我們記住就可以了。

我們現在需要對标題指派,動态改變标題。不廢話,直接上代碼。

App.module.ts 代碼

1 import { NgModule, enableProdMode } from '@angular/core';
 2 import { BrowserModule, Title } from '@angular/platform-browser';
 3 import { AppComponent } from './app.component';
 4 import{InputTextModule}from 'primeng/primeng';
 5 import{FormsModule}from '@angular/forms';
 6 
 7 enableProdMode()
 8 @NgModule({
 9     imports: [BrowserModule,InputTextModule,FormsModule],
10     declarations: [AppComponent],
11     bootstrap: [AppComponent],
12     providers: [Title]
13 })
14 export class AppModule {
15 
16 }      

app.component.ts 代碼

1 import { Component, OnInit, enableProdMode } from '@angular/core';
 2 import { Title } from '@angular/platform-browser';
 3 
 4 @Component({
 5     moduleId: module.id,
 6     selector: 'my-app',
 7     templateUrl: "./app.component.html"
 8 })
 9 
10 export class AppComponent  {
11     name: string;
12     constructor(private title: Title) { }
13     myClick() {
14         console.log("guozhqi" + name);
15         this.title.setTitle(name);
16     }
17    
18 }      

app.component.html

1    <input type="text" [(ngModel)]="name">
2    <button (click)="myClick()">{{name}}</button>
3    {{name}}      

運作效果圖:

Angular2 小貼士 Name

問題來了,我們的标題目前是一堆和xml類型的标簽,我輸入的内容不見了?

我們把app.component.ts 代碼改變一下,

1 import { Component, OnInit, enableProdMode } from '@angular/core';
 2 import { Title } from '@angular/platform-browser';
 3 
 4 @Component({
 5     moduleId: module.id,
 6     selector: 'my-app',
 7     templateUrl: "./app.component.html"
 8 })
 9 
10 export class AppComponent  {
11     name: string;
12     constructor(private title: Title) { }
13     myClick() {
14         console.log("guozhqi" +this. name);
15         this.title.setTitle(this.name);
16     }
17    
18 }      

請對比差別,我們輸出的内容Name加上了this.name ,這樣就可以正确的擷取到結果。

總結:

  1. 任何時候在方法中使用變量,都要加上this
  2. app.component.ts中的變量name,如果不加this指定,擷取的是什麼值呢?期待你得回答
  3. 寫入标題使用依賴注入Title的setTitle方法

小貼士:Name需要我們注意,this記得要加上

有人的地方就有政治,有政治就有鬥争,但我讨厭政治,讨厭無休止的迎合。