zoukankan      html  css  js  c++  java
  • 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记得要加上

  • 相关阅读:
    extjs 为组件动态添加插件
    springboot使用spring-cloud-starter-alibaba-sentinel导致响应变成xml格式
    js 将数据保存到本地
    iframe跨域安全
    nginx url自动301加斜杠
    EXTJS防止表单中回车触发提交
    servlet
    Struts1和Struts2的区别
    AWT和Swing的简记
    sleep()和wait()
  • 原文地址:https://www.cnblogs.com/jiagoushi/p/5964258.html
Copyright © 2011-2022 走看看