显示表中输入的值

时间:2019-06-22 18:18:06

标签: angular5

创建表并单击提交按钮显示值。提交数据时要显示的值

app.component.ts

import { Component } from '@angular/core';
@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})
export class AppComponent {
    title = 'app1';
    private fieldArray: Array<any> = [];
    private newAttribute: any = {};
    addFieldValue() {
        this.fieldArray.push(this.newAttribute)
        this.newAttribute = {};
    }
    /* ngOnInit(){
    console.log(this.fieldArray);
    } */
}

2 个答案:

答案 0 :(得分:0)

使用ngIf来测试所选产品的存在,并将产品名称与标题数据绑定。在组件上创建一个lastlySelected属性,然后onclick将该lastSelected属性设置为所单击产品或产品名称的值。

<h3 style="color:darkmagenta"  *ngIf="recentlySelected" >Recently added products:{{recentlySelected}}</h3>

这里是一个例子:

https://stackblitz.com/edit/angular-ngif-click-zdb9ng?file=app/app.component.html

答案 1 :(得分:0)

您可以在组件类中维护一个recentlyAddedProducts列表,并将新添加的数据推送到该列表中。然后像这样在模板中渲染该列表:

组件类:

recenltyAddedProducts: Array<any> = [];
       private fieldArray: Array<any> = [];
       private newAttribute: any = {};
       addFieldValue() {
       this.fieldArray.push(this.newAttribute)

       this.recenltyAddedProducts.push(this.newAttribute);
       this.newAttribute = {};
       }

具有这样的模板设置:

<h3 style="color:darkmagenta" >Recently added products:</h3>
    <div *ngFor="let p of recenltyAddedProducts">
      <span>
        {{p.productName}}
      </span>
      <span>
        {{p.quantity}}
      </span>

请参阅展示演示的堆栈闪电战

https://stackblitz.com/edit/angular-jvfmfe?file=app/button-overview-example.ts

您可以更新代码以仅显示最近添加的3个产品。

编辑

要仅显示一种最新产品,请进行以下更改:

组件类:

recenltyAddedProduct;
       private fieldArray: Array<any> = [];
       private newAttribute: any = {};
       addFieldValue() {
       this.fieldArray.push(this.newAttribute)

       this.recenltyAddedProduct = this.newAttribute;
       this.newAttribute = {};
       }

具有这样的模板:

<h3 style="color:darkmagenta" >Recently added products:</h3>

      <span>
        {{recenltyAddedProduct?.productName}}
      </span>
      <span>
        {{recenltyAddedProduct?.quantity}}
      </span>

要在h3标签中显示,请具有以下模板:

<h3 style="color:darkmagenta" >Recently added products: <span>
        {{recenltyAddedProduct?.productName}}
      </span>
      <span>
        {{recenltyAddedProduct?.quantity}}
      </span></h3>