无法让@Input()在构造函数中工作(Unable to get @Input() to work inside the constructor)
我创建了两个组件,一个父母和一个孩子。
父级拥有一个名为applications的成员变量:
import { Component, OnInit } from '@angular/core'; import { CoreService } from 'app/core.service'; import { Application } from 'app/models/application.model'; @Component({ selector: 'app-applicationbrowser', templateUrl: './applicationbrowser.component.html', styleUrls: ['./applicationbrowser.component.css'], providers: [CoreService] }) export class ApplicationbrowserComponent { applications: Application[] = [ new Application(1, false, "beef"), new Application(2, false, "teef"), new Application(3, false, "feef") ]; constructor() { } }并在其模板中使用子组件:
<div> <app-resourceitem *ngFor="let item of applications" [item]="item"></app-resourceitem> </div>我认为这是为我的应用程序变量中的每个应用程序调用的。
但是子组件只有一个'未定义'的项目变量:
@Input() item: any; constructor() { debugger; console.log(this.item); //item is always undefined.... }我究竟做错了什么?
I created two components, a parent and a child.
The parent has a member variable called applications:
import { Component, OnInit } from '@angular/core'; import { CoreService } from 'app/core.service'; import { Application } from 'app/models/application.model'; @Component({ selector: 'app-applicationbrowser', templateUrl: './applicationbrowser.component.html', styleUrls: ['./applicationbrowser.component.css'], providers: [CoreService] }) export class ApplicationbrowserComponent { applications: Application[] = [ new Application(1, false, "beef"), new Application(2, false, "teef"), new Application(3, false, "feef") ]; constructor() { } }and uses the child component in its template:
<div> <app-resourceitem *ngFor="let item of applications" [item]="item"></app-resourceitem> </div>I assumed that this gets called for each application in my applications variable.
But the child component only ever has an 'undefined' item variable:
@Input() item: any; constructor() { debugger; console.log(this.item); //item is always undefined.... }What am I doing wrong?
最满意答案
@Input数据在ngOnInit可用,而不是构造函数。
@Component({ ... }) export class SomeChildComponent implements OnInit { @Input() item: any; constructor(){} ngOnInit() { console.log(this.item); } }@Input data is available in ngOnInit, not the constructor.
@Component({ ... }) export class SomeChildComponent implements OnInit { @Input() item: any; constructor(){} ngOnInit() { console.log(this.item); } }更多推荐
发布评论