在使用Angular做双向数据绑定,需求是实现保留搜索记录的功能时出现问题,将input框输入的内容push进数组里面,显示在页面上
#html代码
<div class="page">
<input type="text" [(ngModel)]="keywords"><button (click)="serach()">click</button>
<ul>
<li *ngFor="let item of historyList">{{item}}</li>
</ul>
</div>
#ts代码
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-form',
templateUrl: './form.component.html',
styleUrls: ['./form.component.css']
})
export class FormComponent implements OnInit {
public keywords:string;
public historyList:any[];
constructor() { }
ngOnInit() {
}
serach(){
this.historyList.push(this.keywords)
console.log(this.keywords)
}
}
#运行时报错:Cannot read property ‘push’ of undefined
![在这里插入图片描述](https://img-blog.csdnimg.cn/20191101115205788.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3UwMTAzMjg1MzM=,size_16,color_FFFFFF,t_70)
##这里产生这个问题的原因是因为我在定义historyList发生问题,我只定义了historyList为一个any类型的数组,并未给他赋值,这里只需要先定义数组为空就可以了
export class FormComponent implements OnInit {
public keywords:string;
public historyList:any[]=[];
constructor() { }
ngOnInit() {
}
serach(){
this.historyList.push(this.keywords)
console.log(this.keywords)
}
#重新运行一下,没有问题
![在这里插入图片描述](https://img-blog.csdnimg.cn/20191101115524569.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3UwMTAzMjg1MzM=,size_16,color_FFFFFF,t_70)