Rahul
Rahul

Reputation: 5844

@Input() is not working when selector is enclosed in HTML Tag - Angular 2

In my Angular2 app there is a component called 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);
        }

      }

I am using this component in my AppComponent.

Problem 1

When I use TabTitleComponent in HTML(AppComponent's Template) as following then I am not getting title value. In console it is logging undefined.

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

when I replace it with following then I am getting 88 in console.

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

Problem 2

When I make title of string type and pass value then in both cases I am getting undefined.

I am not able to find the root cause. Can someone helps me to find out the issue.

Upvotes: 0

Views: 298

Answers (2)

Yoav Schniederman
Yoav Schniederman

Reputation: 5391

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

Upvotes: 1

Maks K
Maks K

Reputation: 3914

Maybe the reason in "88" Try this code:

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

Upvotes: 1

Related Questions