当选择器包含在HTML标记 - Angular 2中时,@ Input()不起作用

时间:2017-05-29 12:57:14

标签: angular input angularjs-directive angular2-template

在我的Angular2应用中,有一个名为TabTitleComponent的组件。

       import { Component, OnInit,Input,AfterViewInit } from '@angular/core';

      @Component({
        selector: 'tab-title',
        templateUrl: './tab-title.component.html',
        styleUrls: ['./tab-title.component.css']
      })
      export class TabTitleComponent implements OnInit,AfterViewInit {

        @Input() title;

        ngOnInit()
        {
          console.log('ngOnInit'+this.title);
        }
        ngAfterViewInit()
        {
          console.log('ngAfterViewInit',this.title);
        }

      }

我在AppComponent

中使用此组件
  

问题1

当我在HTML(TabTitleComponent的模板)中使用AppComponent时,我没有获得title值。在控制台中,它正在记录undefined

 <div>
   <tab-title [title]='88'> </tab-title>     
</div>

当我用以下内容替换它时,我在控制台中获得88

 <tab-title [title]='88'> </tab-title>  
  

问题2

当我title string类型并传递值时,我会收到undefined

我无法找到根本原因。有人可以帮我找出问题。

2 个答案:

答案 0 :(得分:1)

也许是&#34; 88&#34; 试试这段代码:

<tab-title [title]="'88'"> </tab-title>  

答案 1 :(得分:1)

//our root app component
import {Component, Input, NgModule, VERSION} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'


@Component({
  selector: 'tab-title',
  template: '<div>{{title}}</div>'
})
export class TabTitleComponent implements OnInit,AfterViewInit {

  @Input() title : string;

  ngOnInit()
  {
    console.log('ngOnInit'+this.title);
  }
  ngAfterViewInit()
  {
    console.log('ngAfterViewInit',this.title);
  }

}

@Component({
  selector: 'my-app',
  template: `
    <div>
     <tab-title [title]="'88'"> </tab-title>     
    </div>
  `,
})
export class App {

}

@NgModule({
  imports: [ BrowserModule ],
  declarations: [ App, TabTitleComponent ],
  bootstrap: [ App ]
})
export class AppModule {}
相关问题