英文:
Why Angular Input is undefined?
问题
我有一个典型的简单情况,但在这种情况下,@Input() 不起作用...
子组件:
@Component({
selector: 'app-test-grid',
templateUrl: './test-grid.component.html',
styleUrls: ['./test-grid.component.scss'],
})
export class TestGridComponent implements OnInit {
@Input() memos: any[];
constructor() {
console.log(this.memos); // 打印undefined
}
ngOnInit() {
console.log(this.memos); // 也打印undefined
}
}
<div *ngIf="checker()">
THIS IS DISPLAYED
<app-test-grid>
[memos]="test"
</app-test-grid>
</div>
// parent component.ts
test: number[] = [1, 2, 3, 4, 5, 6, 7];
ngOnInit() {
console.log(this.test); // 打印[1, 2, 3, 4, 5, 6, 7]
}
checker() {
console.log('checker', this.test.length !== 0); // 这会打印true
return this.test.length !== 0;
}
这段代码有什么问题?这是非常基础的情况...我尝试找了一些相关的帖子,但没有找到答案。
英文:
I have typical easy situation but in that case @Input() does not working...
Child Component:
@Component({
selector: 'app-test-grid',
templateUrl: './test-grid.component.html',
styleUrls: ['./test-grid.component.scss'],
})
export class TestGridComponent implements OnInit {
@Input() memos: any[];
constructor() {
console.log(this.memos); // prints undefined
}
ngOnInit() {
console.log(this.memos); // also prints undefined
}
}
<div *ngIf="checker()">
THIS IS DISPLAYED
<app-test-grid>
[memos]="test"
</app-test-grid>
</div>
// parent component.ts
test: number[] = [1, 2, 3, 4, 5, 6, 7];
ngOnInit() {
console.log(this.test); // print [1,2,3,4,5,6,7]
}
checker() {
console.log('checker', this.test.length !== 0); // this prints true
return this.test.length !== 0;
}
what's wrong with this code? this is very rudimentary case... I tried to found some another posts related but I didn't found answer.
答案1
得分: 2
你关闭了app-test-grid
标签,因此memos
赋值丢失,作为组件的内容。使用以下方式:
<app-test-grid [memos]="test">
</app-test-grid>
英文:
You closed the app-test-grid
tag so the memos
assignment is lost as the content of the component. Use this:
<app-test-grid [memos]="test">
</app-test-grid>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论