【问题标题】:Get input field data by clicking on the button and get value in p element in angular7通过单击按钮获取输入字段数据并在angular7中的p元素中获取值
【发布时间】:2019-11-12 10:26:16
【问题描述】:

我是 Angular 的新手,我的先生给我练习,通过使用 Angular 7 单击按钮来获取 p 元素中的输入字段数据。我使用一些函数(onClick、onClickSubmit、myFunction)做了很多尝试,但我失败了在每一次尝试中。我认为我在数据绑定/事件绑定方面遇到了问题。请帮我解决这个问题。

app.component.html

<input type="text" [(ngModel)]="name" name="name">
<br><br>
<button (Click)="onClick">Show</button>
<p>{{name}}</p>

app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
    title = 'angular7-app';

    show(){
        this.show =
    }
}

【问题讨论】:

标签: angular input angular7 angular-input


【解决方案1】:

试试这样:

Working Demo

.html

<input type="text" [(ngModel)]="name" name="name">
<br>
<br>
<button (click)="show = true">Show</button>
<p *ngIf="show">{{name}}</p>

【讨论】:

  • 在这个例子中数据被删除然后我按退格键,我认为它是双向数据绑定。点击提交按钮后输入数据并删除两边。
【解决方案2】:

只需将输入值放入一个临时变量中,然后在点击时将其复制到显示中。

app.component.ts

tempName : string = '';  // Temp variable to hold input
origName : string = '';  // Name to be displayed

app.component.html

<input type="text" [(ngModel)]="tempName" name="name">

<button (click)="origName=tempName">Show</button>

<p *ngIf="origName!=''">{{origName}}</p>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-07
    • 2019-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多