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}}

 

運行效果圖:

 

問題來了,我們的標題目前是一堆和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記得要加上

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM