Angualr使用双向数据绑定,push输入框的内容到数组里面去的时候报错

mac2025-05-18  27

在使用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

##这里产生这个问题的原因是因为我在定义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) }

#重新运行一下,没有问题

最新回复(0)