以角度推动物体

时间:2020-02-23 12:12:47

标签: angular

我试图将对象按角度显示在矩阵卡中,因此每个输入都有一张卡来容纳三个字段。到目前为止,我无法使用的内容:我收到一条错误消息,提示this.inputField.push is not a function at PostsComponent.getInput

我的HTML:

       <input type="text" placeholder="Your name"  name="name" id="inputField1" [(ngModel)]="inputField.name">
       <input type="text" placeholder="Department" name="department" id="inputField2" [(ngModel)]="inputField.department" >
       <textarea type="text" placeholder="Message" name="message" value="" id="inputField3" [(ngModel)]="inputField.message" ></textarea>
       <button  (click)="getInput()">Post</button>
   </mat-card> 

   <mat-card *ngIf= "hiddenList"  [notes] ="inputField" class="inputField"  >
        <ul *ngIf="show" >
                <li *ngFor= "let input of inputField">
                    {{inputField.name}}
                    {{inputField.department}}
                    {{inputField.message}}
                </li>
              </ul>
  <button type="button" (click)="removeList()">Delete</button>
   </mat-card>

组件Ts文件:

import { Component } from '@angular/core';
import { InputField } from '../posts/posts'

@Component({
  selector: 'app-posts',
  templateUrl: './posts.component.html',
  styleUrls: ['./posts.component.scss']
})
export class PostsComponent {
hiddenList=false

inputField: InputField[] = [];

getInput(){
     this.show = true
     this.inputField.push({'name':this.name, 'department':this.department, 'message':this.message})
     }

removeList(){
   this.hiddenList = true
  }
}

Post.ts:

export interface InputField{
 name: string,
 department: string, 
 message: string
}

3 个答案:

答案 0 :(得分:1)

我检查了您的代码,发现有几个错误。请在这里找到完整的代码,我在这里创建了一个有效的stackblitz-https://stackblitz.com/edit/angular-gw5rrv

为了您的成长,我在这里列出错误:

  • 您将inputField与不正确的ngModel输入配合使用。当我们想将值存储在inputField数组中时,我们需要一些其他变量来与ngModel绑定(我已经创建了fieldData)。
  • 您应该在* ngFor中使用模板输入变量(在您的情况下为input),但您正在使用inputField。
    • 我还删除了不必要的代码
    • 为简单起见,我使用div代替了mat-card

如有任何疑问,请告诉我。

答案 1 :(得分:0)

尝试在构造函数中初始化变量。

constructor(){
    this.inputField = [];
}

答案 2 :(得分:0)

您绑定到inputField属性,例如inputField.name,inputField.department, 但是在声明中,您说它是一个数组。然后将其初始化为空数组。

您应该具有2个属性:

inputFields: InputField[] = [] 
inputField: InputField = {} 

查看您当前编辑的数据。

然后可以将当前编辑的inputField推入inputFields数组。

this.inputFields.push(this.inputField);

(我先前的回答被否决了,但我仍然认为您应该在声明末尾使用;))