2017-05-29 70 views
0

在我的Angular2应用程序中有一个名为TabTitleComponent的组件。当选择器包含在HTML标记中时@Input()不工作 - Angular 2

 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 TabTitleComponentAppComponent的模板)如下然后,我没有得到title值。在控制台中,它正在记录undefined

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

当我用下面的代替它然后我在控制台中得到88

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

问题2

当我做stringtitle,然后传递价值在两种情况下我得到undefined

我无法找到根本原因。有人能帮我找出问题吗?

回答

1

也许在 “88” 的原因 试试这个代码:

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

使用' “ '名'”'这是工作之后。真奇怪 。为什么这样? @Max – Dalvik

+2

“name” - 在ts文件和“'name'”中是可变的 - 只是一个字符串。 –

+0

明白了。当我使用'''名称'“时它的工作状态为 – Dalvik

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 {} 
+0

。其工作背后的原因是什么? – Dalvik

+0

输入格式为[InputName] =“参数” –