gpt4 book ai didi

javascript - ngfor let var of vars --> 遍历整个数组 + 1

转载 作者:行者123 更新时间:2023-11-30 15:26:38 25 4
gpt4 key购买 nike

我正在学习 angular2,我发现了一些奇怪的东西。我有一个消息列表,我想遍历整个列表以在其他组件中显示我的消息:

import { Component } from '@angular/core';


@Component({
selector: 'my-message-list',
template: `<ul><my-message *ngFor="let message of messages" [message]="message"> </my-message></ul>`,
})
export class ListMessages {
messages :Array<Object>
constructor(){
this.messages = [] ;
//this.messages.push({text:'zerg'});
this.messages.push({text:'lolz1'});
this.messages.push({text:'lolz2'});
this.messages.push({text:'lolz3'});
this.messages.push({text:'lolz4'});

}

}
import {Component, Input} from '@angular/core';

@Component({
selector: 'my-message',
template: `<li >{{ message.text }}</li>`,
})
export class Message {
@Input() message:{text:string}
constructor(){
}
ngOnInit() {
if(typeof this.message === 'undefined'){
this.message = {text:'o_O'};
}

debugger;
}
}

通过我的调试器,我注意到在第一次迭代时一切正常。我有一个:

<ul><!--template bindings={
"ng-reflect-ng-for-of": "[object Object],[object Object],[object Object],[object Object]"
}--><my-message ng-reflect-message="[object Object]" ng-version="2.4.10"><li>lolz1</li></my-message><my-message ng-reflect-message="[object Object]"><li>lolz2</li></my-message><my-message ng-reflect-message="[object Object]"><li>lolz3</li></my-message><my-message ng-reflect-message="[object Object]"><li>lolz4</li></my-message></ul>

但是在这次迭代之后,它会再用一次 undefined 并用 o_O 替换第一个项目

<ul><!--template bindings={
"ng-reflect-ng-for-of": "[object Object],[object Object],[object Object],[object Object]"
}--><my-message ng-reflect-message="[object Object]" ng-version="2.4.10"><li>o_O</li></my-message><my-message ng-reflect-message="[object Object]"><li>lolz2</li></my-message><my-message ng-reflect-message="[object Object]"><li>lolz3</li></my-message><my-message ng-reflect-message="[object Object]"><li>lolz4</li></my-message></ul>

所以它不起作用,但为什么?

最佳答案

因为您还在 @NgModule 中引导 Message 组件

@NgModule({
imports: [ BrowserModule ],
declarations: [ ListMessages,Message ],
bootstrap: [ ListMessages,Message ]
})
export class AppModule { }

删除它并像这样更新它:

@NgModule({
imports: [ BrowserModule ],
declarations: [ ListMessages,Message ],
bootstrap: [ ListMessages]
})
export class AppModule { }

关于javascript - ngfor let var of vars --> 遍历整个数组 + 1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42862547/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com