我有兩個組件,Full-Layout(父組件)和Department(子組件)。Angular2 Input()變量打印undefined
當Full-Layout中的變量綁定並傳遞給子組件時,它總是聲稱它是未定義的。我不知道爲什麼。
full-layout.component.html
<ul class="nav-dropdown-items">
<li class="nav-item" *ngFor="let item of dropDownItems">
<a #clicked class="nav-link" routerLinkActive="active" [routerLink]="[item.routerLink]">
<i class="icon-puzzle"></i>{{item.name}}
<app-departments [title]="childTitle"></app-departments>
</a>
</li>
</ul>
full-layout.component.ts
import {
Component,
OnInit
} from '@angular/core';
@Component({
selector: 'app-dashboard',
templateUrl: './full-layout.component.html',
})
export class FullLayoutComponent implements OnInit {
public childTitle: string = 'This text is passed to child';
constructor() {}
ngOnInit(): void {}
dropDownItems = [{
routerLink: '/departments',
name: 'Artshums'
},
{
routerLink: '/components/social-buttons',
name: 'Dentistry'
},
{
routerLink: '/components/cards',
name: 'Law'
},
{
routerLink: '/components/forms',
name: 'IOPPN'
},
{
routerLink: '/components/modals',
name: 'LSM'
},
{
routerLink: '/departments',
name: 'NMS'
},
{
routerLink: '/components/tables',
name: 'Nursing'
},
{
routerLink: '/components/tabs',
name: 'SSPP'
},
{
routerLink: '/components/tabs',
name: 'Health'
}
];
}
departments.component.ts
import {Component, OnInit, Input} from '@angular/core';
@Component({
selector: 'app-departments',
templateUrl: './departments.component.html',
inputs: ['title']
})
export class DepartmentsComponent implements OnInit {
@Input()
title:string;
constructor() {}
ngOnInit() {
console.log(this.title);
}
}
departments.module.ts
@NgModule({
imports: [
DepartmentsRoutingModule,
CommonModule,
MaterialModule.forRoot()
],
declarations: [ DepartmentsComponent ]
})
export class DepartmentsModule {}
app.module.ts
// imports {...}...
// assume necessary imports above
@NgModule({
imports: [
BrowserModule,
AppRoutingModule,
DepartmentsModule,
],
declarations: [
AppComponent,
FullLayoutComponent,
],
schemas: [CUSTOM_ELEMENTS_SCHEMA]
bootstrap: [ AppComponent ]
})
export class AppModule { }
我得到undefined
消息,當我在我的子組件打印標題。
任何想法如何解決這個問題?
謝謝香榭麗舍!
嘗試擺脫裝飾器中的「inputs」屬性並調用控制檯登錄ngOnChanges – chrispy
對不起,我是Angular2的新手,你能否縮寫? @chrispy – DingDong