【问题标题】:How to reload a component with a new list?如何使用新列表重新加载组件?
【发布时间】:2019-03-03 06:16:51
【问题描述】:

我想通过单击带有新列表的按钮来重新加载我的组件。所以我的问题是,单击其中一个按钮后,它不会使用新列表重新加载组件。有人可以帮我吗?非常感谢。

这是我交出清单的 HTML 文件。

<div class="content_box_left" *ngIf="isloaded==true">
  <component [list]="actualList"></component>
</div>

我的 Typescript-File 中的一些代码:

actualList=[];
list1=[1, 2, 3, "dog"];
list2=[3, "cat", "mouse", 47];

button1(){
   console.log("Button 1 pressed");
   this.actualList=this.list1;
}
button2(){
   console.log("Button 2 pressed");
   this.actualList=this.list2;
}

组件-HTML-代码:

<div>
    <ion-list>
        <ion-item *ngFor="let list of list">
            <ion-label>{{list}}</ion-label>
        </ion-item>
    </ion-list>
</div>

组件-Typescript-代码:

@Component({
  selector: 'caiditems',
  templateUrl: 'caiditems.html'
})
export class CaiditemsComponent {

  @Input()
  list = []; 
  constructor() {}    
 }
}

【问题讨论】:

  • 出了什么问题
  • 点击按钮后不会重新加载组件。所以应该改变的列表没有改变。
  • 你能发布“组件”打字稿代码吗?
  • 从组件添加代码
  • 组件工作正常。如果我用项目填充实际列表,它将通过访问侧面显示。但是用新列表刷新不起作用...

标签: html angular ionic3 components


【解决方案1】:

找出问题所在。 *ngFor 在数组或列表发生某些更改后不会更新。使用 trackBy 是我的问题的解决方案:https://netbasal.com/angular-2-improve-performance-with-trackby-cc147b5104e5

【讨论】:

    【解决方案2】:

    这里有错误

    actualList=[];
    list1=[1, 2, 3, dog];
    list2=[3, cat, mouse, 47];
    

    改成

    actualList=[];
    list1=[1, 2, 3, 'dog'];
    list2=[3, 'cat', 'mouse', 47];
    

    dog、cat、mouse 是需要单引号的字符串。其余的代码都很好。看看我的stackblitz。我用了你的代码

    https://stackblitz.com/edit/angular-zbvh8k?file=src%2Fapp%2Fapp.component.html

    【讨论】:

    • 不,那是通过更改我的列表元素的错误。我认为问题是我的组件 html 文件中有一个离子标签?
    • 做一件事,在 CaiditemsComponent 和 console.log(this.list) 中实现 ngOnChanges 并告诉我单击按钮时它会打印什么。
    • 嗯,您能解释一下在哪里以及如何进行吗?以前从未这样做过
    猜你喜欢
    • 2013-04-16
    • 2018-02-22
    • 2019-10-14
    • 2015-08-29
    • 2013-01-13
    • 2018-08-13
    • 2019-04-27
    • 1970-01-01
    • 2020-05-20
    相关资源
    最近更新 更多